using System;
using System.Collections.Generic;
using System.Text;
using SCG.SolarVengeanceEngine;
using SCG.SolarVengeanceEngine.BrainInfo;
using System.Windows;
using System.Drawing;

//STRATEGO 4 V4.5.3
//STRATEGO 4 is 8975 lines long!
/*
Version Releases
>4.0.1: Stratego 4 Initial Release. 
*4.0.3: Fixed some unusual bugs that caused runtime errors.
!4.1.1: Stratego 4 now handles alliances very well.
*4.1.3: Enhanced multiplayer performance and better communications.
>4.2.1: Stratego 4 is now adapted to spread out clusters like MirrorImage.
>4.2.2: Improved overall gameplay for Stratego 4.
>4.2.3: Streamlined the startillery and spyship build code.
*4.2.4: Fixed the Startillery bunker code to accept 2 to 5 character starship codes, not only the usual three character codes. 
        Fixed some flaws with ED.
>4.2.5: Added the capability to build and use the 4 new starships.
>4.3.0: Refinied ST4s strategy to squeeze out even more combat effectiveness. 
>4.3.1: Added an enemy starship field to make the brain remember where the most active regions are. Stratego 4 now reacts 
        differently to large enemy starships. Enhanced close combat game performance.
!4.3.2: More intelligent Cavalry Attack orders. Also I have improved the multiplayer gameplay enormously and fixed many 
        overlooked bugs. I have also fixed up the entire code of Stratego 4 into regions so that Visual Studio editors don't have 
        to search endlessly for bits of code that Stratego 4 use to do its actions. Added code to prevent overbuilding drone defenses.
        I discovered that Stratego 4 does better in close combat games if he just built a wave of fast drones first then expand.
!4.4.0: I made an important improvements to ST4's warship attack code. St4 will no longer blindly attack stars that he doesn't know. 
        St4 now prioritizes his warship orders. He will attempt to take valuable enemy stars during expand mode if needed. 
        The warships he orders can now be reordered to a better target if the target they are currently on can't be conquered at this 
        time. You can now give ST4 basic intelligence like where the enemy capital is. Fixed a bug with capital rush attack. Fixed 
        a bug with the spyship build code. When the brain transitions into the backdoor task, he doesn't build the spyship needed.
        Stratego 4 has been massively upgraded (mostly in the alliance area).
*4.4.1  Fixed and improved the SIAM navigation system. I have a special debugger installed that can read info from the SIAM 
        navigation as a graphical display. This debugger explains why ST4's script has a huge increase in line count from the last 
        version (8111 to 8461).. CRITICAL UPDATE: I fixed a critical memory leak on Stratego 4 that made ST4 run slower as the game 
        went on. This fix removes the possibility of SV5 crashing during gameplay! I have also imporved the alliances yet again, and 
        improved teamwork!
>4.4.2  Focused on improving gameplay for Stratego 4.
*4.5.0  Fixed annoying abnormal resource count when playing KR or higher. Also fixed a potential resource leak on the big stars.
        Preparing this brain for SV6.0 Silverlight! Also added the advanced techship algorithm that avoids blackholes.
!4.5.1  Added the ability for the brain to repair its starships by the pulsar. Also improved the spyship/scanship algorithm to find 
        the closest clear spot in a nebula. Also I have improved SIAM again! Now it detects if a part of the map is crowded 
        with starships. When St4's capital blitz attack fails, if there are nearby stars to take, the warships will take over those stars.
        Also, if ST4 suspects that your capital is in a nebula, he will blindly attack it.
*4.5.2  Removed built in debugger for preparation for SV6.0 debugging tools!
!4.5.3  Fixed a loophole that caused St4 to ally with more than half of the active players in the game. 
        I have added support for Ultra high resource games up to 10,000 resources at startup.
        Still waiting for the debugger to be completed.

 Stratego 4 reconizes these commands in multiplayer. These commands are not case sensitive.
 *1 take me over                  Stratego 4 will prompt you if you want him to take you over.
 *2 conquer me                    same as *1
 *3 "star name" is a capital      Tells Stratego 4 where you saw an enemy capital.
 *4 capital at "star name"        same as *3
 *5 conquer "star name"           Tells Stratego 4 what star to take over.
 *6 take "star name"              same as *5
 *7 attack "star name"            same as *5
 *8 alliance?                     Tells Stratego 4 that you want an alliance. -
 *9 ally with me?                 same as *7 -
 *10 do you want to ally with me? same as *7 -
 *11 ally?                        same as *7 -
 *12 attack now                   Signals stratego 4 to attack the enemy capital with its existing forces.
 *                                If stratego 4 is going to sneak attack, this command will get the brain 
 *                                to move its spyship towards the enemy capital. Signalling attack again will 
 *                                order the warships to attack the capital.
 *13 attack                       same as *12
 
 - Requires that you address Stratego 4 with "St4", "Stratego 4", or Stratego4's listed name.
   Example: St4, -message-  
   Note: if you use "St4" or "Stratego 4", you are addressing to all instances of Stratego 4 in the game.
 
 ! Important update, fixed bugs that can cause problems with Stratego4's gameplay.
 > Improvements made to Stratego4, No bug fixes made this update.
 * Priority update, fixed a bug that caused Stratego4 to generate errors.
 */

namespace SCG.SolarVengeance.Brains
{
    //***********************************************************************************************************************
    //***********************************************************************************************************************
    //*************************************** THE CODE FOR THE BRAIN ********************************************************

    public class Stratego4 : Brain
    {
        public override ChallengeLevel Challenge
        {
            get
            {
                return ChallengeLevel.Extreme;
            }
        }

        //private members
        #region Dictionaries
        private Dictionary<string, int> _shipTask = new Dictionary<string, int>();
        private Dictionary<string, StarSystemInfo> _shipTargetOrder = new Dictionary<string, StarSystemInfo>();
        private Dictionary<string, bool> _ExpandOrder = new Dictionary<string, bool>();
        private Dictionary<string, bool> _StarCovered = new Dictionary<string, bool>();
        private Dictionary<string, StarSystemInfo> _MyStar = new Dictionary<string, StarSystemInfo>();
        private Dictionary<string, bool> _StarSecured = new Dictionary<string, bool>();
        private Dictionary<string, int> _StarSecureTime = new Dictionary<string, int>();
        private Dictionary<string, int> _LastStarOwner = new Dictionary<string, int>();
        private Dictionary<string, int> _GetStarTValue = new Dictionary<string, int>();
        private Dictionary<string, int> _GetStarAttacks = new Dictionary<string, int>();
        private Dictionary<string, int> _StarMaxShields = new Dictionary<string, int>();
        private Dictionary<string, int> _StarClaim = new Dictionary<string, int>();
        private Dictionary<string, bool> _MyBorderScan = new Dictionary<string, bool>();
        private Dictionary<string, int> _TShields = new Dictionary<string, int>();
        private Dictionary<string, int> _TAValue = new Dictionary<string, int>();
        private Dictionary<string, int> _TDefenders = new Dictionary<string, int>();
        private Dictionary<string, int> _EnShipsNearStar = new Dictionary<string, int>();
        private Dictionary<string, string> _EnShipList = new Dictionary<string, string>();
        private Dictionary<string, int> _BattleStationSlots = new Dictionary<string, int>();
        private Dictionary<string, StarShipInfo> _BeamShipTarget = new Dictionary<string, StarShipInfo>();
        private Dictionary<string, int> _GravShipDragComplete = new Dictionary<string, int>();
        private Dictionary<string, int> _shipStarted = new Dictionary<string, int>();
        private Dictionary<int, StarShipType> _UsefulStarships = new Dictionary<int, StarShipType>();
        private Dictionary<int, string> _ReadMessage = new Dictionary<int, string>();
        private Dictionary<int, string> _SentByPlayer = new Dictionary<int, string>();
        private Dictionary<string, bool> _EnemyHasMines = new Dictionary<string, bool>();
        private Dictionary<string, int> _RecoveryTime = new Dictionary<string, int>();
        private Dictionary<string, int> _LastKnownShields = new Dictionary<string, int>();
        private Dictionary<Point, int> _EnemyIntensity = new Dictionary<Point, int>();
        private Dictionary<Point, int> _DronesToThis = new Dictionary<Point, int>();
        private Dictionary<int, StarShipInfo> _LargeEnemy = new Dictionary<int, StarShipInfo>();
        private Dictionary<string, int> _AllianceViolations = new Dictionary<string, int>();
        private Dictionary<string, int> _WarshipWeaponsNearStar = new Dictionary<string, int>();
        private Dictionary<string, string> _PlayerOrder = new Dictionary<string, string>();
        private Dictionary<string, StarSystemInfo> _PlayerCapital = new Dictionary<string, StarSystemInfo>();
        private Dictionary<int, StarShipInfo> _WarShipList = new Dictionary<int, StarShipInfo>();
        private Dictionary<string, int> _EshipsNearAlly = new Dictionary<string, int>();

        //Implementing a prototype Trust Level
        private Dictionary<string, double> _TrustLevel = new Dictionary<string, double>();
        #endregion

        #region Lists
        private List<string> _WordInMessage = new List<string>();
        #endregion

        #region Private Variables
        private bool debuggerenabled = false;
        private int StoredEnemyLocations = 0;
        private int Countdown = -1;
        private int waittime = 50;
        private bool ExecuteBlock = false;
        private bool EDModeInit = false;
        private bool ThisISED = false;
        private int Clusterx = 0;
        private int Clustery = 0;
        private int CapitalTask = -1;
        private int FaultPoints = 0;
        private bool InitStarData = false;
        private bool InitAttacks = false;
        private int startingresources = -1;
        private StarSystemInfo[] ECAPITAL = new StarSystemInfo[12];
        private string currecaptar = "";
        private string[] ECAPITALOWNER = new string[12];
        private int[] laststarsowned = new int[12];
        private int ewpn = 6;
        private int minewpn = 999;
        private int calattacks = 2;
        private double CApp = 32767.9;
        private bool EnemySighted = false;
        private int[] MaxSTRange = new int[11];
        private bool InitMaxSTRange = false;
        private bool TEStartillery = false;
        private bool[] PlayerHasStartillery = new bool[12];
        private bool CalAttack = false;
        private int scanshipmode = -1;
        private int scanshipreturn = -1;
        private bool scanshipattack = false;
        private int scanshipdirection = -1;
        private int MsgState = 0;
        private string MsgStateName = "";
        private int messagestate = 0;
        private int alertmessage = 0;
        private int totalmessagesreceived = 0;
        private int numplayers = -1;
        private string tmpOwner = "null";
        private bool firstSee = false;
        private int LargeEnemies = 0;
        private int knownstars = -1;
        private int knownstarshields = 0;
        private bool closecombatmode = false;
        private bool CloakedOpponent = false;
        private int impulsetime = 0;
        private StarSystemInfo oldecap = null;
        #endregion

        //***************************************************************************************************************//

        //These methods below should be commented out once it is installed in SV6.0 engine
        private void PrintToDebug(string Message, bool AddToDebug)
        {
            //if (AddToDebug == true)
                //tmpform.debugstring = tmpform.debugstring + Message + Convert.ToChar(13) + Convert.ToChar(10);
        }
        private void ShowDebugScreen()
        {
            //Shows the string that the brain generated. Must be able to copy the entire string easily.
            SendMessage(ChatChannel.All, "Attention, " + Name + " is experiencing technicial diffuculties and must be debugged.");
        }
        private void ClearDebugScreen()
        {
            //Clears the temporary string that holds the debug info.
        }

        //***************************************************************************************************************//

        //description
        public override string Description
        {
            get
            {
                return "01/17/08 - 08/10/09: Fleet Admiral Stratego v4.5.3 by Beat2k, now the Stratego Series brain has taken on a new form. " +
                       "Stratego 4 can ally with players, communicate with players, and work with players unlike his counterparts. " +
                       "Stratego 4 can play 20R, 100R, KR (1000R) and higher, and Extreme Duel. " +
                       "Stratego 4 is built up even more with better gameplay, improved intelligence, and " +
                       "improved algorithms. I warn you, Stratego 4 plays very well in every mode so play your absolute best! " +
                       "Stratego 4 must have at least one star to start each game or it will not work properly. It doesn\'t matter if it is a capital or not." + Environment.NewLine + Environment.NewLine +
                       "Now Stratego 4 can take you on in Solar Vengeance 6 and it\'s tougher than ever!";
            }
        }

        #region Stratego4's overrides
        public override void IncomingMessage(string playerName, string message)
        {
            totalmessagesreceived++;
            _ReadMessage.Add(_ReadMessage.Count, message);
            _SentByPlayer.Add(_SentByPlayer.Count, playerName);
        }

        //author info
        public override string Author
        {
            get
            {
                return "Beat2k";
            }
        }

        //select starships
        private StarShipType debugstarship;
        private bool testbuild = false;
        private bool builddebug = false;
        public override List<StarShipType> AvailableShipTypes
        {
            get
            {
                List<StarShipType> avail = new List<StarShipType>();

                builddebug = false;
                debugstarship = StarShipType.JumpGateShip;

                //clear previously selected starships. this is used to transistion betweeen ED and Standard.
                avail.Clear();

                //Add the 6 starships this brain starts with.
                //ED mode changes two of stratego 3's strships in his setup.
                if (builddebug == true)
                    //Test Starship (for debugging only!!! set builddebug to false when done!)
                    avail.Add(debugstarship);
                else
                    avail.Add(StarShipType.InkSpot);

                avail.Add(StarShipType.WarShip);
                avail.Add(StarShipType.TechShip);
                avail.Add(StarShipType.StarTillery);
                if (CheckForED() == true)
                {
                    avail.Add(StarShipType.HijackShip);
                    avail.Add(StarShipType.CloakDetector);
                }
                else
                {
                    avail.Add(StarShipType.Drone);
                    avail.Add(StarShipType.SpyShip);
                }
                return avail;
            }
        }
        #endregion

        //***************************************************************************************************************//

        #region Custom Subroutenes

        private int GetDirectionDifference(int BaseDirection, int TargetDirection, bool AbsoluteValue)
        {
            int a = 0;
            int c = BaseDirection;
            int d = TargetDirection;
            while ((c >= 16) | (c < 0))
            {
                if (c < 0) c = c + 16;
                else c = c - 16;
            }
            while ((d >= 16) | (d < 0))
            {
                if (d < 0) d = d + 16;
                else d = d - 16;
            }
            a = c - d;
            if (a > 8) a = a - 16;
            else if (a <= -8) a = 16 + a;
            if (AbsoluteValue == true)
                if (a < 0) a = 0 - a;
            return a;
        }

        private bool IsFullyAllied(string OtherPlayer)
        {
            bool btm = ((AlliedWith(OtherPlayer) != AllianceLevel.None) & (AlliedWithMe(OtherPlayer) != AllianceLevel.None));
            return btm;
        }

        private bool DangerObjectWithinArea(int dX, int dY, int dWidth, int dHeight)
        {
            bool danger = false;
            foreach (WormholeInfo whinfo in Wormholes)
            {
                if (whinfo.X >= dX && whinfo.Y >= dY && whinfo.X <= dX + dWidth && whinfo.Y >= dY + dHeight)
                    danger = true;
            }
            foreach (BlackHoleInfo whinfo in BlackHoles)
            {
                if (whinfo.X >= dX && whinfo.Y >= dY && whinfo.X <= dX + dWidth && whinfo.Y >= dY + dHeight)
                    danger = true;
            }
            return danger;
        }

        private StarSystemInfo FindStarName(string StarName)
        {
            StarSystemInfo sys;
            StarSystemInfo rv = null;
            for (int d = 0; d < StarSystems.Count; d++)
            {
                sys = StarSystems[d];
                if (sys.Name.ToLower() == StarName.ToLower())
                {
                    rv = sys;
                }
            }
            return rv;
        }

        //this routene returns the wormhole the starship will use to get to destination
        //null if the wormhole path is not specified or the path to and from destination is longer than the straightfowared path.
        private WormholeInfo WormHoleWayFaster(StarShipInfo thisSS, int destx, int desty)
        {
            WormholeInfo TWormhole = null;
            int diffx = 0;
            int diffy = 0;
            int directdistance = 0;
            int altdistance1 = 0;
            int altdistance2 = 0;
            int closesttodest = 32767;
            foreach(WormholeInfo whinfo in Wormholes)
            {
                if (whinfo.DestinationKnown == true)
                {
                    diffx = Math.Abs(thisSS.X - destx);
                    diffy = Math.Abs(thisSS.Y - desty);
                    if (diffx > diffy) directdistance = diffx;
                    else directdistance = diffy;
                    diffx = Math.Abs(thisSS.X - whinfo.X);
                    diffy = Math.Abs(thisSS.Y - whinfo.Y);
                    if (diffx > diffy) altdistance1 = diffx;
                    else altdistance1 = diffy;
                    diffx = (int)Math.Abs(destx - whinfo.Destination.X);
                    diffy = (int)Math.Abs(desty - whinfo.Destination.Y);
                    if (diffx > diffy) altdistance2 = diffx;
                    else altdistance2 = diffy;

                    if ((directdistance - 10 >= altdistance1 + altdistance2) & (closesttodest > altdistance1 + altdistance2))
                    {
                        closesttodest = altdistance1 + altdistance2;
                        TWormhole = whinfo;
                    }
                }
            }
            return TWormhole;
        }

        private WormholeInfo ClosestWormhole(int x, int y, int maxdistance, bool destknown)
        {
            WormholeInfo TWormhole = null;
            int diffx = 0;
            int diffy = 0;
            int ddistance = 0;
            int dclosest = maxdistance;
            foreach (WormholeInfo whinfo in Wormholes)
            {
                if (whinfo.DestinationKnown == destknown)
                {
                    diffx = Math.Abs(x - whinfo.X);
                    diffy = Math.Abs(y - whinfo.Y);
                    ddistance = diffx + diffy;
                    if (ddistance < dclosest)
                    {
                        dclosest = ddistance;
                        TWormhole = whinfo;
                    }
                }
            }
            return TWormhole;
        }

        private PulsarInfo ClosestSecuredPulsar(int X, int Y, int maxDistance, List<bool> tPulsarSecureList)
        {
            PulsarInfo ps = null;
            int bx = X;
            int by = Y;
            int maxdist = maxDistance;
            if (tPulsarSecureList.Count == Pulsars.Count)
            {
                for (int d = 0; d < Pulsars.Count; d++)
                {
                    if ((DistanceQuick(bx, by, Pulsars[d].X, Pulsars[d].Y) < maxdist) & (tPulsarSecureList[d] == true))
                    {
                        ps = Pulsars[d];
                        maxdist = DistanceQuick(bx, by, Pulsars[d].X, Pulsars[d].Y);
                    }
                }
            }
            return ps;
        }

        //***************************************************************************************************************//

        //determine if this game is an ED game
        public bool CheckForED()
        {
            bool thisised = false;
            int Stars = StarSystems.Count;
            bool estarp1 = false;
            bool estarp2 = false;
            int startingvalue = 0;
            if (Stars == 2)
            {
                foreach (StarSystemInfo sys in StarSystems)
                {
                    if ((sys.OwnedByMe == true) & (sys.IsCapital == true))
                        startingvalue = sys.Value;
                    if ((sys.X <= 4) & (sys.Y <= 4))
                        estarp1 = true;
                    if ((sys.X >= 45) & (sys.Y >= 45))
                        estarp2 = true;
                }
                if ((startingvalue == 999) & (estarp1 == true) & (estarp2 == true))
                    thisised = true;
            }
            return thisised;
        }

        //Get Star System List Index
        private int GetStarSystemIndex(string starname)
        {
            int ad = -1;
            int sind = 0;
            foreach (StarSystemInfo sys in StarSystems)
            {
                if (sys.Name == starname) ad = sind;
                sind = sind + 1;
            }
            return ad;
        }

        //find 8 bit general direction
        private int FindDirection8(double disttarx, double disttary, double tantar)
        {
          // no problem with this code.
          double modt;
          int direction = 0;
          modt = Math.Round(tantar * 1000);
          if (tantar < 0.0)
          {
            if (modt > -414)
            {
              if (disttarx < 0) direction = 7; 
              else direction = 3;
            }
            if (modt < -2414)
            {
              if (disttary < 0) direction = 1;
              else direction = 5;
            }
            if ((modt >= -2414) & (modt <= -414))
            {
              if (disttarx < 0) direction = 6;
              else direction = 2;
            }
          }
          if (tantar > 0.0)
          {
            if (modt < 414)
            {
              if (disttarx < 0) direction = 7;
              else direction = 3;
            }
            if (modt > 2414)
            {
              if (disttary < 0) direction = 1; 
              else direction = 5;
            }
            if ((modt <= 2414) & (modt >= 414))
            {
              if (disttarx < 0) direction = 8;
              else direction = 4;
            }
          }
          if (tantar == 0)
          {
            if (disttarx < 0) direction = 7; 
            else if (disttarx > 0) direction = 3;
            if (disttary < 0) direction = 1; 
            else if (disttary > 0) direction = 5;
          }
          return direction;
        }

        //find 16 bit general direction  for SIAM navigation
        public int FindDirection16(double basex, double basey, double targetx, double targety)
        {
            double bx = basex;
            double by = basey;
            double tx = targetx;
            double ty = targety;
            double radians = Math.PI / 180;
            double modt = 0;
            int direction = 0;

            bx = tx - bx;
            by = ty - by;
            modt = Math.Sqrt((bx * bx) + (by * by));
            modt = by / modt;

            if (modt <= -1) modt = -0.99999999999999999999999999;
            if (modt >= 1) modt = 0.99999999999999999999999999;
            modt = Math.Asin(modt);

            if (bx > 0)
                modt = (modt / radians) + 90;
            else
                modt = 180 - (modt / radians) + 90;

            if ((modt >= 348.75) | (modt < 11.25))
                direction = 1;
            else if ((modt >= 11.25) & (modt < 33.75))
                direction = 2;
            else if ((modt >= 33.75) & (modt < 56.25))
                direction = 3;
            else if ((modt >= 56.25) & (modt < 78.75))
                direction = 4;
            else if ((modt >= 78.75) & (modt < 101.25))
                direction = 5;
            else if ((modt >= 101.25) & (modt < 123.75))
                direction = 6;
            else if ((modt >= 123.75) & (modt < 146.25))
                direction = 7;
            else if ((modt >= 146.25) & (modt < 168.75))
                direction = 8;
            else if ((modt >= 168.75) & (modt < 191.25))
                direction = 9;
            else if ((modt >= 191.25) & (modt < 213.75))
                direction = 10;
            else if ((modt >= 213.75) & (modt < 236.25))
                direction = 11;
            else if ((modt >= 236.25) & (modt < 258.75))
                direction = 12;
            else if ((modt >= 258.75) & (modt < 281.25))
                direction = 13;
            else if ((modt >= 281.25) & (modt < 303.75))
                direction = 14;
            else if ((modt >= 303.75) & (modt < 326.25))
                direction = 15;
            else if ((modt >= 326.25) & (modt < 348.75))
                direction = 16;

            return direction;
        }

        public bool IsAdjacentToCoords(StarShipInfo ship, int cX, int cY)
        {
            int x = cX;
            int y = cY;
            if (ship.X >= x - 1 && ship.Y >= y - 1 && ship.X <= x + 1 && ship.Y <= y + 1)
                return true;

            return false;
        }

        public void RemoveDebugMessages()
        {
            string debugstring;
            if (_ReadMessage.Count > 0)
            {
                for (int d = 0; d < totalmessagesreceived; d++)
                {
                    if (_ReadMessage.ContainsKey(d) == true)
                    {
                        debugstring = _ReadMessage[d].ToLower();
                        if (debugstring.Length >= 5)
                        {
                            debugstring = debugstring.Substring(0, 5);
                            if (debugstring == "debug")
                            {
                                if (_ReadMessage.ContainsKey(d) == true)
                                {
                                    _ReadMessage.Remove(d);
                                    _SentByPlayer.Remove(d);
                                }
                            }
                        }
                    }
                }
            }
        }
        #endregion

        //***************************************************************************************************************//

        private bool EnD = true;  //Enable Debugging?

        //main Brain logic
        public override void Execute()
        {
            try
            {
                ClearDebugScreen();
                PrintToDebug("Official Debug Output for " + Name + " made at " + DateTime.Now.ToString(), EnD);

                #region Header Information
                int[] redirect;
                StarSystemInfo[] enemystar;
                StarShipInfo[] enemyship;
                StarShipInfo[] visship;
                StarSystemInfo[] visstar;
                StarShipInfo[] alliedship;
                StarShipInfo[] EWarship;
                StarSystemInfo ssi = null;
                int Stars;
                int Ships;
                int s = 0;
                int i = 0;
                int mapx = 0;
                int mapy = 0;
                StarSystemInfo stari = null;
                StarShipInfo shipi = null;
                double calculation;
                int NumWormholes = 0;
                int NumBlackholes = 0;
                int NumPulsars = 0;

                Stars = StarSystems.Count;
                Ships = StarShips.Count;
                NumBlackholes = BlackHoles.Count;
                NumWormholes = Wormholes.Count;
                NumPulsars = Pulsars.Count;

                redirect = new int[16];
                enemystar = new StarSystemInfo[Stars];
                enemyship = new StarShipInfo[Ships + 1];
                visstar = new StarSystemInfo[Stars];
                alliedship = new StarShipInfo[Ships + 1];
                visship = new StarShipInfo[Ships + 1];
                EWarship = new StarShipInfo[Ships + 1];

                mapx = MapWidth;
                mapy = MapHeight;

                //Players still in the game
                int playersactive = 0;
                foreach (string playername in PlayerNames)
                {
                    if (playername != "")
                    {
                        playersactive = playersactive + 1;
                        //Initialize Trust level variables
                        if (_TrustLevel.ContainsKey(playername) == false)
                            _TrustLevel.Add(playername, 100);
                        if (_AllianceViolations.ContainsKey(playername) == false)
                            _AllianceViolations.Add(playername, 0);
                    }
                }
                if (numplayers == -1)
                    numplayers = playersactive;

                //Remove Debug Messages
                RemoveDebugMessages();

                //Determine if this scenario is the genuine ED.
                if (EDModeInit == false)
                {
                    ThisISED = CheckForED();
                    EDModeInit = true;
                }

                #endregion

                PrintToDebug("------------------Header Information----------------", EnD);
                PrintToDebug("PlayersLeftInGame=" + playersactive.ToString() + " NumberOfPlayersInGame=" + numplayers.ToString() + " ThisIsED=" + ThisISED.ToString(), EnD);
                PrintToDebug("TotalStarSystems=" + Stars.ToString() + " TotalStarShips=" + Ships.ToString() + " MapSizeCoordinates=" + mapx.ToString() + "," + mapy.ToString(), EnD);
                PrintToDebug("VisibleWormHoles=" + NumWormholes.ToString() + " VisibleBlackHoles=" + NumBlackholes.ToString() + " VisiblePulsars=" + NumPulsars.ToString(), EnD);

                if (ThisISED == false)
                {
                    //This is not ED so execute normal script
                    // Find the center of the cluster

                    #region Initialization
                    long sumx = 0;
                    long sumy = 0;
                    double divisonx = 0;
                    double divisony = 0;
                    foreach (StarSystemInfo sys in StarSystems)
                    {
                        sumx = sumx + sys.X;
                        sumy = sumy + sys.Y;
                    }
                    divisonx = sumx / Stars;
                    divisony = sumy / Stars;
                    Clusterx = Convert.ToInt32(divisonx);
                    Clustery = Convert.ToInt32(divisony);

                    if (impulsetime == 0)
                    {
                        impulsetime = 1;
                        //TriggerDebugScreen(true);
                    }
                    else
                        impulsetime = impulsetime + 10;

                    if (CapitalTask == -1)
                    {
                        CapitalTask = 0;
                        FaultPoints = 0;
                    }
                    //if (InitStarData == true)
                    //{
                    //    SendMessage(ChatChannel.All, "Init Star");
                    //}

                    _UsefulStarships.Clear();
                    _UsefulStarships.Add(0, StarShipType.CommandShip);  //CSs
                    _UsefulStarships.Add(1, StarShipType.CloakDetector);  //CDs
                    _UsefulStarships.Add(2, StarShipType.BeamShip); //MSs
                    _UsefulStarships.Add(3, StarShipType.RepairShip); //RSs
                    _UsefulStarships.Add(4, StarShipType.EMine); //EMs
                    _UsefulStarships.Add(5, StarShipType.HijackShip); //HJs
                    _UsefulStarships.Add(6, StarShipType.ShieldGenerator);  //SGs
                    _UsefulStarships.Add(7, StarShipType.MineSweeper); //ESs
                    _UsefulStarships.Add(8, StarShipType.BattleStation);  //BSs
                    _UsefulStarships.Add(9, StarShipType.MadBomb);  //MBs
                    _UsefulStarships.Add(10, StarShipType.StarTillery);  //STs
                    _UsefulStarships.Add(11, StarShipType.SpyShip);  //SSs
                    _UsefulStarships.Add(12, StarShipType.ScanShip);  //SSs
                    _UsefulStarships.Add(13, StarShipType.InkSpot);
                    _UsefulStarships.Add(14, StarShipType.Drone);
                    _UsefulStarships.Add(15, StarShipType.WarShip); //WSs
                    _UsefulStarships.Add(16, StarShipType.DoppleShip); //also WSs
                    _UsefulStarships.Add(17, StarShipType.ParalyShip); //PSs
                    _UsefulStarships.Add(18, StarShipType.Elite); //also WSs
                    _UsefulStarships.Add(19, StarShipType.RemoteViewer); //RVs
                    #endregion

                    PrintToDebug("--------StarSystem Intelligence--------", EnD);

                    #region StarSystem Intelligence

                    //Gather Intelligence from stars
                    int unknowns = Stars;
                    int mystars = 0;
                    int targets = 0;
                    //int attackedstars = 0;
                    //int totalattacks = 0;
                    int mx = 0;
                    int my = 0;
                    int starsinnebula = 0;
                    int visiblestars = 0;
                    int alliedstars = 0;
                    int myalliedstars = 0;
                    int NumGoodStars = 0;
                    int highestresources = 0;
                    int enemystars = 0;
                    StarSystemInfo mycap = null;
                    StarSystemInfo mylargeststar = null;
                    int largest = 0;
                    int mycapx = -1;
                    int mycapy = -1;
                    StarSystemInfo[] TStar = new StarSystemInfo[Stars];
                    int[] starsowned = new int[12];
                    StarSystemInfo[] mystar = new StarSystemInfo[Stars];
                    StarSystemInfo[] alliedstar = new StarSystemInfo[Stars];
                    StarSystemInfo[] myalliedstar = new StarSystemInfo[Stars];
                    int[] Melees = new int[Stars];
                    int[] SG = new int[Stars];
                    int[] intalliedstar = new int[Stars];
                    bool[] borderstar = new bool[Stars + 1];
                    StarSystemInfo[] enborderscan = new StarSystemInfo[Stars + 1];
                    enborderscan[Stars] = null;
                    borderstar[Stars] = false;
                    Dictionary<string, int> clusterdensity = new Dictionary<string, int>();
                    List<StarSystemInfo> _NebulaStar = new List<StarSystemInfo>(); //NebulaStar shows the number of unknown stars in a nebula
                    s = 0;
                    foreach (StarSystemInfo sys in StarSystems)
                    {
                        SG[s] = 0;
                        TStar[s] = null;
                        Melees[s] = 0;
                        mystar[s] = null;
                        enemystar[s] = null;
                        borderstar[s] = false;
                        enborderscan[s] = null;
                        clusterdensity.Add(sys.Name, 0);
                        if (_LastStarOwner.ContainsKey(sys.Name) == false)
                        {
                            _LastStarOwner.Add(sys.Name, -1);
                            _GetStarTValue.Add(sys.Name, 8);
                            _StarClaim.Add(sys.Name, 0);
                            _StarSecured.Add(sys.Name, false);
                            _StarSecureTime.Add(sys.Name, 0);
                            _StarMaxShields.Add(sys.Name, 0);
                            _StarCovered.Add(sys.Name, false);
                            _GetStarAttacks.Add(sys.Name, -1);
                            _ExpandOrder.Add(sys.Name, true);
                            _MyBorderScan.Add(sys.Name, false);
                            _TShields.Add(sys.Name, 16);
                            _TAValue.Add(sys.Name, 0);
                            _TDefenders.Add(sys.Name, 0);
                            _EnShipsNearStar.Add(sys.Name, 0);
                            _EnShipList.Add(sys.Name, "EOF");
                            _GravShipDragComplete.Add(sys.Name, 0);
                            _RecoveryTime.Add(sys.Name, 0);
                            _LastKnownShields.Add(sys.Name, 999);
                            _WarshipWeaponsNearStar.Add(sys.Name, 0);
                        }
                        _WarshipWeaponsNearStar[sys.Name] = 0;
                        //PrintToDebug("endInit", EnD);
                        if (sys.OwnerInt > -1)
                        {
                            starsowned[sys.OwnerInt]++;
                        }

                        if (sys.OwnedByMe == true)
                        {
                            //PrintToDebug("MyStar", EnD);
                            if (largest < sys.Value)
                            {
                                largest = sys.Value;
                                mylargeststar = sys;
                            }
                            myalliedstars = myalliedstars + 1;
                            myalliedstar[myalliedstars - 1] = sys;
                            //deactivate autobuild if activated.
                            if (sys.AutoStarShip == true)
                                SetAutoStarShip(sys, false);
                            if (sys.Resources > highestresources)
                                highestresources = sys.Resources;
                            if (InitAttacks == false)
                            {
                                _GetStarAttacks[sys.Name] = 0;
                                _StarMaxShields[sys.Name] = 0;
                            }
                            if (_StarClaim[sys.Name] == 0)
                            {
                                _StarClaim[sys.Name] = 1;
                                _StarSecureTime[sys.Name] = 2;
                                _StarSecured[sys.Name] = false;
                            }
                            else
                            {
                                if (_StarSecureTime[sys.Name] > 0)
                                    _StarSecureTime[sys.Name] = _StarSecureTime[sys.Name] - 1;
                                else
                                    _StarSecured[sys.Name] = true;
                            }
                            if (_StarMaxShields[sys.Name] > sys.Shields)
                            {
                                _GetStarAttacks[sys.Name] = _GetStarAttacks[sys.Name] + 1;
                                _RecoveryTime[sys.Name] = (_GetStarAttacks[sys.Name] * 2) + 4;
                            }
                            if (_RecoveryTime[sys.Name] > 0)
                                _RecoveryTime[sys.Name]--;
                            _StarMaxShields[sys.Name] = sys.Shields;
                            unknowns = unknowns - 1;
                            if (sys.Value > 0)
                            {
                                mystars = mystars + 1;
                                mystar[mystars - 1] = sys;
                                //_MyStar[sys.Name] = sys;
                            }
                            if (_LastStarOwner[sys.Name] < 1)
                                _LastStarOwner[sys.Name] = 1;
                            if (sys.IsCapital == true)
                            {
                                _StarSecured[sys.Name] = true;
                                mycap = sys;
                                mycapx = sys.X;
                                mycapy = sys.Y;
                            }
                            if (sys.Value >= 12)
                                NumGoodStars++;
                            _LastKnownShields[sys.Name] = sys.Shields;
                        }
                        else
                        {
                            //PrintToDebug("OtherStar", EnD);
                            //Process Stars that I don't own.
                            _WarshipWeaponsNearStar[sys.Name] = 0;
                            if (_StarMaxShields[sys.Name] > -1)
                            {
                                _GetStarAttacks[sys.Name] = _GetStarAttacks[sys.Name] + 1;
                                _StarMaxShields[sys.Name] = -1;
                            }
                            if (_ExpandOrder[sys.Name] == false)
                                _ExpandOrder[sys.Name] = true;
                            if (sys.Visible == true)
                            {
                                _LastKnownShields[sys.Name] = sys.Shields;
                                _TShields[sys.Name] = sys.Shields;
                                if (_LastStarOwner[sys.Name] < 0)
                                    _LastStarOwner[sys.Name] = 0;
                            }
                            else
                            {
                                if (_StarClaim[sys.Name] > 0)
                                {
                                    _LastKnownShields[sys.Name] = 16;
                                    _StarClaim[sys.Name] = 0;
                                }
                            }

                            if (sys.OwnerInt > -1)
                            {
                                //PrintToDebug("Not Neutral", EnD);
                                if (_EnemyHasMines.ContainsKey(sys.Owner) == false)
                                    _EnemyHasMines.Add(sys.Owner, false);

                                if (_StarClaim[sys.Name] > 0)
                                {
                                    if (_AllianceViolations[sys.Owner] > 2)
                                    {
                                        _AllianceViolations[sys.Owner]++;
                                        _TrustLevel[sys.Owner] = _TrustLevel[sys.Owner] / 2;
                                        if (AlliedWith(sys.Owner) != AllianceLevel.None)
                                        {
                                            SendMessage(ChatChannel.Friendly, sys.Owner + ", please stop attacking my stars or I will no longer ally with you.");
                                        }
                                    }
                                    else
                                    {
                                        _AllianceViolations[sys.Owner]++;
                                        if (AlliedWith(sys.Owner) != AllianceLevel.None)
                                        {
                                            _TrustLevel[sys.Owner] = _TrustLevel[sys.Owner] - sys.Value;
                                            SendMessage(ChatChannel.Friendly, sys.Owner + ", please stop attacking my stars.");
                                        }
                                        else
                                        {
                                            _TrustLevel[sys.Owner] = _TrustLevel[sys.Owner] / 2;
                                        }
                                    }
                                    _StarClaim[sys.Name] = 0;
                                }
                                if ((AlliedWith(sys.Owner) == AllianceLevel.None) | (AlliedWithMe(sys.Owner) == AllianceLevel.None))
                                {
                                    //PrintToDebug("Enemy", EnD);
                                    visiblestars = visiblestars + 1;
                                    visstar[visiblestars - 1] = sys;
                                }
                                if ((AlliedWith(sys.Owner) != AllianceLevel.None) & (AlliedWithMe(sys.Owner) != AllianceLevel.None))
                                {
                                    //PrintToDebug("Allied", EnD);
                                    alliedstars = alliedstars + 1;
                                    alliedstar[alliedstars - 1] = sys;
                                    myalliedstars = myalliedstars + 1;
                                    myalliedstar[myalliedstars - 1] = sys;
                                    //intalliedstar[alliedstars - 1] = s;
                                }
                                _LastKnownShields[sys.Name] = sys.Shields;
                                if (_LastStarOwner[sys.Name] <= 0)
                                    _LastStarOwner[sys.Name] = 1;
                                if (sys.IsCapital == true)
                                {
                                    //PrintToDebug("eCapital", EnD);
                                    ECAPITAL[sys.OwnerInt] = sys;
                                    ECAPITALOWNER[sys.OwnerInt] = sys.Owner;
                                }
                            }
                            else
                            {
                                if (_LastStarOwner[sys.Name] == 1)
                                {
                                    visiblestars = visiblestars + 1;
                                    visstar[visiblestars - 1] = sys;
                                }
                            }
                            //PrintToDebug("endOwn", EnD);
                            if (_LastStarOwner[sys.Name] == 1)
                            {
                                _WarshipWeaponsNearStar[sys.Name] = 999;
                            }
                            if ((sys.OwnerInt > -1) | (_LastStarOwner[sys.Name] == 1) | (_LastStarOwner[sys.Name] == -1))
                            {
                                if ((AlliedWith(sys.Owner) == AllianceLevel.None) | (AlliedWithMe(sys.Owner) == AllianceLevel.None))
                                {
                                    enemystars = enemystars + 1;
                                    enemystar[enemystars - 1] = sys;
                                }
                            }
                            if (_LastStarOwner[sys.Name] != -1)
                                unknowns = unknowns - 1;
                            if ((AlliedWith(sys.Owner) == AllianceLevel.None) | (AlliedWithMe(sys.Owner) == AllianceLevel.None))
                            {
                                targets = targets + 1;
                                TStar[targets - 1] = sys;
                            }
                            //PrintToDebug("PLayer Orders", EnD);
                            if (_PlayerOrder.ContainsKey("Conquer" + sys.Owner) == true)
                            {
                                if (sys.Name == _PlayerOrder["Conquer" + sys.Owner])
                                {
                                    targets = targets + 1;
                                    TStar[targets - 1] = sys;
                                }
                            }
                            if (_PlayerOrder.ContainsKey("Take" + sys.Name) == true)
                            {
                                targets = targets + 1;
                                TStar[targets - 1] = sys;
                            }
                            if (_PlayerOrder.ContainsKey("Cap" + sys.Name) == true)
                            {
                                //ECapital index of 10 is used to see if that star is a capital or not.
                                ECAPITAL[10] = sys;
                                if ((sys.OwnerInt > -1) & ((ECAPITALOWNER[10] == "") | (ECAPITALOWNER[10] != null))) 
                                    ECAPITALOWNER[10] = sys.Owner;
                            }
                            //PrintToDebug("endOrders", EnD);
                        }
                        //PrintToDebug("LastInit", EnD);
                        if (_TAValue.ContainsKey(sys.Name) == true)
                            _TAValue[sys.Name] = 0;
                        if (_TDefenders.ContainsKey(sys.Name) == true)
                            _TDefenders[sys.Name] = 0;

                        if (_MyBorderScan[sys.Name] == true)
                            _MyBorderScan[sys.Name] = false;

                        if (_LastStarOwner[sys.Name] == -1)
                        {
                            //if target has not been explored, assume shields to be 6;
                            _TShields[sys.Name] = 9;
                        }
                        else
                        {
                            _TShields[sys.Name] = _LastKnownShields[sys.Name];
                        }

                        if ((sys.Visible == true) | (sys.OwnedByMe == true))
                        {
                            calculation = _TShields[sys.Name] * 2;
                            calculation = sys.Value - calculation;
                            calculation = calculation + (sys.Resources / 3);
                            calculation = calculation + (sys.Scanners / 5) - 1;
                            _GetStarTValue[sys.Name] = Convert.ToInt32(calculation);
                        }
                        //PrintToDebug("endStar", EnD);

                        if ((GetTerrain(sys.X, sys.Y) == TerrainType.Nebula) & (_LastStarOwner[sys.Name] == -1))
                        {
                            _NebulaStar.Add(sys);
                        }
                        s = s + 1;
                    }
                    if (InitStarData == false)
                    {
                        InitStarData = true;
                    }
                    if (InitAttacks == false)
                    {
                        InitAttacks = true;
                    }
                    s = 0;
                    if (mycap == null)
                    {
                        mycap = mylargeststar;
                    }
                    else
                    {
                        if (startingresources == -1) startingresources = mycap.Resources;
                    }

                    Dictionary<string, AllianceLevel> tmpalliancelevel = new Dictionary<string, AllianceLevel>();
                    string tmpstrplay = "";
                    for (int d = 0; d < playersactive; d++)
                    {
                        if (tmpalliancelevel.ContainsKey(PlayerNames[d]) == false)
                        {
                            tmpalliancelevel.Add(PlayerNames[d], AllianceLevel.None);
                        }
                        else
                        {
                            tmpalliancelevel[PlayerNames[d]] = AllianceLevel.None;
                        }
                    }

                    //calculate cluster density for each star I own
                    for (int d = 0; d < mystars; d++)
                    {
                        clusterdensity[mystar[d].Name] = 0;
                        for (int dd = 0; dd < mystars; dd++)
                        {
                            if ((Distance(mystar[d].X, mystar[d].Y, mystar[dd].X, mystar[dd].Y) <= 8) & (d != dd))
                            {
                                clusterdensity[mystar[d].Name]++;
                            }
                        }
                    }

                    starsinnebula = _NebulaStar.Count;

                    PrintToDebug("MyStars=" + mystars.ToString() + " DangerStars=" + enemystars.ToString() + " TargetStars=" + targets.ToString() + " AlliedStars=" + alliedstars.ToString() + " EnemyStars=" + visiblestars.ToString() + " UnknownStars=" + unknowns.ToString(), EnD);
                    PrintToDebug("StarsNearCapital=" + knownstars.ToString() + " NebulaStars=" + starsinnebula.ToString(), EnD);

                    //If a player breaks an alliance with me, make sure I am not allied with him.
                    for (int d = 0; d < playersactive; d++)
                    {
                        PrintToDebug("DEBUG PLAYER " + PlayerNames[d], EnD);
                        if (_EshipsNearAlly.ContainsKey(PlayerNames[d]) == false)
                            _EshipsNearAlly.Add(PlayerNames[d], 0);
                        else
                            _EshipsNearAlly[PlayerNames[d]] = 0;
                        if (_TrustLevel.ContainsKey(PlayerNames[d]) == true)
                        {
                            if (AlliedWithMe(PlayerNames[d]) == AllianceLevel.None)
                            {
                                if ((AlliedWith(PlayerNames[d]) == AllianceLevel.Formal) & (MsgState == 0))
                                {
                                    SendMessage(ChatChannel.All, PlayerNames[d] + ", Why did you break alliances with me?");
                                    SetAlliance(PlayerNames[d], AllianceLevel.None);
                                    tmpalliancelevel[PlayerNames[d]] = AllianceLevel.None;
                                    _TrustLevel[PlayerNames[d]] = _TrustLevel[PlayerNames[d]] / 2;
                                }
                                else if ((AlliedWith(PlayerNames[d]) != AllianceLevel.None) & (MsgState == 0))
                                {
                                    SetAlliance(PlayerNames[d], AllianceLevel.None);
                                    tmpalliancelevel[PlayerNames[d]] = AllianceLevel.None;
                                    _TrustLevel[PlayerNames[d]] = _TrustLevel[PlayerNames[d]] / 1.2;
                                }
                            }
                            else
                            {
                                if (_TrustLevel[PlayerNames[d]] <= 25)
                                {
                                    if (AlliedWith(PlayerNames[d]) != AllianceLevel.None)
                                    {
                                        SendMessage(ChatChannel.All, PlayerNames[d] + ", I\'m no longer going to ally with you.");
                                        SetAlliance(PlayerNames[d], AllianceLevel.None);
                                        tmpalliancelevel[PlayerNames[d]] = AllianceLevel.None;
                                    }
                                }
                            }
                            //gain the player's trust if he does not attack my stars, but attacks other stars.
                            if ((starsowned[d] > laststarsowned[d]) & (starsowned[mycap.OwnerInt] >= laststarsowned[mycap.OwnerInt]))
                            {
                                if ((AlliedWithMe(PlayerNames[d]) != AllianceLevel.None) & (AlliedWith(PlayerNames[d]) != AllianceLevel.None))
                                {
                                    _TrustLevel[PlayerNames[d]] = _TrustLevel[PlayerNames[d]] * 1.05;
                                }
                            }
                        }
                        else
                        {
                            _TrustLevel.Add(PlayerNames[d], 100);
                            _AllianceViolations.Add(PlayerNames[d], 0);
                        }
                    }
                    if (knownstars == -1)
                    {
                        knownstars = 0;
                        knownstarshields = 0;
                        foreach (StarSystemInfo sys2 in StarSystems)
                            if (sys2.OwnedByMe == false)
                                if (Distance(sys2.X, sys2.Y, mycapx, mycapy) <= 12)
                                {
                                    knownstars++;
                                    if (sys2.Visible == true)
                                        knownstarshields = knownstarshields + sys2.Shields;
                                    else
                                        knownstarshields = knownstarshields + 20;
                                }
                    }

                    for (int d = 0; d < _NebulaStar.Count; d++)
                    {
                        PrintToDebug("NS:" + _NebulaStar[d].Name, EnD);
                    }

                    #endregion

                    PrintToDebug("capital management", EnD);
                    //Contains Triggered DEBUGS!
                    #region Capital Management Code
                    //Capital Management Code
                    bool SE = false;
                    StarSystemInfo Ecap = null;
                    bool[] isallied = new bool[12];
                    int alliedplayers = 1;
                    int Ecapx = -1;
                    int Ecapy = -1;
                    int capitalx = -1;
                    int capitaly = -1;
                    string EcapOwner = "";
                    int numcapitals = 0;
                    double closest = 36767.9;
                    double capdist = 0;
                    double EShipADist = 0;
                    i = 0;
                    for (int d = 0; d < 11; d++)
                    {
                        isallied[d] = false;
                        if (ECAPITAL[d] != null)
                        {
                            if ((ECAPITALOWNER[i] != "") & (ECAPITALOWNER[i] != null))
                            {
                                if ((AlliedWith(ECAPITALOWNER[d]) != AllianceLevel.None) & (AlliedWithMe(ECAPITALOWNER[d]) != AllianceLevel.None))
                                {
                                    alliedplayers++;
                                    isallied[d] = true;
                                    for (int ade = 0; ade < StarShips.Count; ade++)
                                    {
                                        if (IsFullyAllied(StarShips[ade].Owner) == false)
                                        {
                                            EShipADist = Distance(ECAPITAL[d].X, ECAPITAL[d].Y, StarShips[ade].X, StarShips[ade].Y);
                                            if (EShipADist < 6 + (TechMultiple / 2))
                                            {
                                                if (StarShips[ade].IdentifiedByMe == true)
                                                    _EshipsNearAlly[ECAPITALOWNER[d]] = _EshipsNearAlly[ECAPITALOWNER[d]] + StarShips[ade].Value;
                                                else if (StarShips[ade].KnownWeapons >= 3)
                                                    _EshipsNearAlly[ECAPITALOWNER[d]] = _EshipsNearAlly[ECAPITALOWNER[d]] + StarShips[ade].KnownWeapons;
                                                else
                                                    _EshipsNearAlly[ECAPITALOWNER[d]] = _EshipsNearAlly[ECAPITALOWNER[d]] + ewpn;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    PrintToDebug("capital management 2", EnD);

                    while (i <= 10)
                    {
                        s = Random(0, 100);
                        if (ECAPITAL[i] != null)
                        {
                            if ((ECAPITALOWNER[i] != "") & (ECAPITALOWNER[i] != null))
                            {
                                PrintToDebug("capital management 3-0  i=" + i.ToString(), EnD);
                                //Erase old capital data if capital is conquered
                                if ((ECAPITAL[i].Visible == true) & (ECAPITAL[i].IsCapital == false))
                                {
                                    if ((ECAPITAL[i].OwnedByMe == false) & (i <= 9))
                                    {
                                        if (AlliedWithMe(ECAPITAL[i].Owner) != AllianceLevel.None)
                                        {
                                            if (s > 67)
                                                SendMessage(ChatChannel.All, "Way to go " + ECAPITAL[i].Owner + "!");
                                            else if (s > 33)
                                                SendMessage(ChatChannel.All, "Goog job " + ECAPITAL[i].Owner + "!");
                                            else
                                                SendMessage(ChatChannel.All, "That\'s fine work you did there " + ECAPITAL[i].Owner + "!");
                                            _TrustLevel[ECAPITAL[i].Owner] = _TrustLevel[ECAPITAL[i].Owner] * 2;
                                            _AllianceViolations[ECAPITAL[i].Owner]--;
                                        }
                                        else
                                        {
                                            if (s > 67)
                                                SendMessage(ChatChannel.All, "Oh man " + ECAPITAL[i].Owner + "!");
                                            else if (s > 33)
                                                SendMessage(ChatChannel.All, "Dang it " + ECAPITAL[i].Owner + "!");
                                            else
                                                SendMessage(ChatChannel.All, "OH NOOOO! " + ECAPITAL[i].Owner + "!");
                                            _TrustLevel[ECAPITAL[i].Owner] = _TrustLevel[ECAPITAL[i].Owner] / 2;
                                            _AllianceViolations[ECAPITAL[i].Owner]++;
                                        }
                                    }
                                    if (_PlayerOrder.ContainsKey("Cap" + ECAPITAL[i].Name) == true)
                                    {
                                        //TriggerDebugScreen(true, "NO CAPITAL");
                                        _PlayerOrder.Remove("Cap" + ECAPITAL[i].Name);
                                    }
                                    ECAPITAL[i] = null;
                                    ECAPITALOWNER[i] = "";
                                }
                            }
                            else
                            {
                                if ((ECAPITAL[i].Visible == true) & (ECAPITAL[i].IsCapital == false))
                                {
                                    if (_PlayerOrder.ContainsKey("Cap" + ECAPITAL[i].Name) == true)
                                    {
                                        //TriggerDebugScreen(true, "NO CAPITAL V2");
                                        _PlayerOrder.Remove("Cap" + ECAPITAL[i].Name);
                                        ECAPITAL[i] = null;
                                        ECAPITALOWNER[i] = "";
                                    }
                                }
                            }
                        }

                        //Send a message to the player to confirm an alliance unless there are only two players remaining or I have alled with at least half of the players.
                        if (ECAPITAL[i] != null)
                        {
                            if ((ECAPITALOWNER[i] != "") & (ECAPITALOWNER[i] != null))
                            {
                                PrintToDebug("capital management 3-1  EcapOwner:" + ECAPITALOWNER[i] + " ECAP:"+ ECAPITAL[i].Name, EnD);

                                if (_PlayerCapital.ContainsKey(ECAPITALOWNER[i]) == false)
                                    _PlayerCapital.Add(ECAPITALOWNER[i], ECAPITAL[i]);
                                numcapitals++;
                                //if (_PlayerOrder.ContainsKey("Cap" + ECAPITAL[i].Name) == false)
                                //    _PlayerOrder.Add("Cap" + ECAPITAL[i].Name, "Capital");
                                if ((playersactive > 2) & (alliedplayers < playersactive / 2))
                                {
                                    if ((MsgState == 0) & (AlliedWith(ECAPITALOWNER[i]) == AllianceLevel.None))
                                    {
                                        //send message if I see a player's capital close to me
                                        capitalx = ECAPITAL[i].X;
                                        capitaly = ECAPITAL[i].Y;
                                        capdist = DistanceQuick(mycapx, mycapy, capitalx, capitaly);
                                        if ((((capdist <= 30) & (AlliedWithMe(ECAPITALOWNER[i]) == AllianceLevel.Formal)) | (AlliedWithMe(ECAPITALOWNER[i]) == AllianceLevel.Visibility)) & (_TrustLevel[ECAPITALOWNER[i]] >= 50))
                                        {
                                            tmpalliancelevel[ECAPITALOWNER[i]] = AlliedWithMe(ECAPITAL[i].Owner);
                                            SendMessage(ChatChannel.All, ECAPITAL[i].Owner + ", alliance acceped. Switch to allies channel please.");
                                            SetAlliance(ECAPITALOWNER[i], AlliedWithMe(ECAPITAL[i].Owner));
                                        }
                                        else if ((capdist <= 30) & (MsgState == 0) & (_TrustLevel[ECAPITALOWNER[i]] >= 50))
                                        {
                                            MsgState = 1;
                                            MsgStateName = ECAPITALOWNER[i];
                                            if (s > 67)
                                                SendMessage(ChatChannel.All, ECAPITALOWNER[i] + ", Alliance?");
                                            else if (s > 33)
                                                SendMessage(ChatChannel.All, ECAPITALOWNER[i] + ", Do you want to ally with me?");
                                            else
                                                SendMessage(ChatChannel.All, ECAPITALOWNER[i] + ", Ally with me?");
                                        }
                                    }
                                }
                                else
                                {
                                    if ((AlliedWith(ECAPITALOWNER[i]) != AllianceLevel.None) & (AlliedWith(ECAPITALOWNER[i]) != AllianceLevel.Formal))
                                    {
                                        //Break temporary alliance with player
                                        SetAlliance(ECAPITALOWNER[i], AllianceLevel.None);
                                        tmpalliancelevel[ECAPITALOWNER[i]] = AllianceLevel.None;
                                        SendMessage(ChatChannel.All, ECAPITALOWNER[i] + ", you are on your own now.");
                                    }
                                }
                            }
                        }
                        //Check to see if capital object still exists. Don't count the capital as a target if it is allied.
                        if (ECAPITAL[i] != null)
                        {
                            if ((AlliedWith(ECAPITALOWNER[i]) == AllianceLevel.None) | (AlliedWithMe(ECAPITALOWNER[i]) == AllianceLevel.None))
                            {
                                SE = true;
                                capitalx = ECAPITAL[i].X;
                                capitaly = ECAPITAL[i].Y;
                                capdist = DistanceQuick(mycapx, mycapy, capitalx, capitaly);
                                if (capdist < closest)
                                {
                                    closest = capdist;
                                    Ecap = ECAPITAL[i];
                                    Ecapx = capitalx;
                                    Ecapy = capitaly;
                                    EcapOwner = ECAPITALOWNER[i];
                                }
                            }
                        }
                        
                        i = i + 1;
                    }

                    PrintToDebug("special processing", EnD);

                    if (mycap != null)
                    {
                        if ((starsowned[mycap.OwnerInt] < Stars / 10) & (starsowned[mycap.OwnerInt] < laststarsowned[mycap.OwnerInt]) & (playersactive > 2) & (alliedplayers + 1 < playersactive / 2) & (MsgState == 0))
                        {
                            SendMessage(ChatChannel.All, "Help! Someone ally with me?");
                            MsgState = 3;
                        }
                    }

                    //if there are stars that I have not yet seen, and I can't see them with a spyship because of nebula, take a blind guess of capital location.
                    if ((unknowns <= starsinnebula) & (SE == false) & (starsinnebula > 0))
                    {
                        if (_PlayerOrder.ContainsKey("Cap" + _NebulaStar[0].Name) == false)
                        {
                            SendMessage(ChatChannel.Friendly, "Ok, I\'m guessing where his capital is. It must be StarSystem " + _NebulaStar[0].Name + " in that nebula.");
                            _PlayerOrder.Add("Cap" + _NebulaStar[0].Name, "Capital");
                            numcapitals++;
                            //TriggerDebugScreen(true, "CAPITAL IS IN NEBULA! Star:" + _NebulaStar[0].Name);

                            SE = true;
                            ECAPITAL[10] = _NebulaStar[0];
                            capitalx = _NebulaStar[0].X;
                            capitaly = _NebulaStar[0].Y;
                            capdist = DistanceQuick(mycapx, mycapy, capitalx, capitaly);
                            if (capdist < closest)
                            {
                                closest = capdist;
                                Ecap = _NebulaStar[0];
                                Ecapx = capitalx;
                                Ecapy = capitaly;
                                EcapOwner = "";
                            }
                        }
                    }

                    PrintToDebug("EnemyCapitalSighted=" + SE.ToString(), EnD);
                    PrintToDebug("alliance management", EnD);
                    #endregion

                    #region Alliance Management
                    //Check to see if someone is allied with me before sending messages into the allies channel.
                    bool alliedcheck = false;
                    bool closetocapital = false;
                    for (int d = 0; d < 10; d++)
                        if (isallied[d] == true)
                            alliedcheck = true;

                    //If the player decide to change alliance status, do so, but with discernment.
                    for (int d = 0; d < playersactive; d++)
                    {                    
                        if ((AlliedWithMe(PlayerNames[d]) != AllianceLevel.None) & (playersactive > 2))
                        {
                            if ((MsgState == 1) & (MsgStateName == PlayerNames[d]))
                            {
                                SendMessage(ChatChannel.All, PlayerNames[d] + ", alliance made. Switch to allies channel please.");
                                MsgState = 0;
                                SetAlliance(PlayerNames[d], AlliedWithMe(PlayerNames[d]));
                                tmpalliancelevel[PlayerNames[d]] = AlliedWithMe(PlayerNames[d]);
                            }
                            // If someone wants a peace treaty, accept the treaty only if there are more than one player that is not allied with me.
                            if ((AlliedWithMe(PlayerNames[d]) == AllianceLevel.NonAggression) & (alliedplayers + 1 < playersactive / 2) &
                                (AlliedWith(PlayerNames[d]) != AllianceLevel.NonAggression) & (_TrustLevel[PlayerNames[d]] > 25))
                            {
                                tmpalliancelevel[PlayerNames[d]] = AlliedWithMe(PlayerNames[d]);
                                SetAlliance(PlayerNames[d], AlliedWithMe(PlayerNames[d]));
                            }
                            // If someone wants visibility, confirm the capital's location before revealing intelligence
                            if ((AlliedWithMe(PlayerNames[d]) == AllianceLevel.Visibility) & (alliedplayers + 1 < playersactive / 2) &
                                (AlliedWith(PlayerNames[d]) != AllianceLevel.Visibility) & (_TrustLevel[PlayerNames[d]] > 105))
                            {
                                SetAlliance(PlayerNames[d], AlliedWithMe(PlayerNames[d]));
                                tmpalliancelevel[PlayerNames[d]] = AlliedWithMe(PlayerNames[d]);
                            }
                            // If someone wants a formal alliance, confirm the capital's location
                            if ((AlliedWithMe(PlayerNames[d]) == AllianceLevel.Formal) &
                                ((capdist <= 30) | (_TrustLevel[PlayerNames[d]] > 110)) &
                                (alliedplayers + 1 < playersactive / 2) & (AlliedWith(PlayerNames[d]) != AllianceLevel.Formal) &
                                (_TrustLevel[PlayerNames[d]] > 110))
                            {
                                SetAlliance(PlayerNames[d], AlliedWithMe(PlayerNames[d]));
                                tmpalliancelevel[PlayerNames[d]] = AlliedWithMe(PlayerNames[d]);
                            }
                        }
                    }

                    if (SE == true)
                    {
                        PrintToDebug("DistanceToECap=" + closest.ToString() + " ECapName=" + Ecap.Name + " ECapOwner=" + EcapOwner, EnD);
                        if ((EcapOwner != tmpOwner) & (alliedcheck == true))
                        {
                            tmpOwner = EcapOwner;
                            SendMessage(ChatChannel.Friendly, "Everyone, I saw an enemy capital at StarSystem " + Ecap.Name);
                            if (CapitalTask == 1)
                            {
                                SendMessage(ChatChannel.Friendly, "You guys need to follow my spyship and wait for my signal to attack..");
                            }
                            else
                            {
                                SendMessage(ChatChannel.Friendly, "Get ready to attack the capital head on.");
                            }
                        }

                    }

                    //SendMessage(ChatChannel.All, "Debug0.9");

                    //Handle alliance messages
                    string tmpstr1 = "";
                    PlayerCommunications msgpl;
                    msgpl = new PlayerCommunications();
                    if (_ReadMessage.Count > 0)
                    {
                        for (int d = 0; d < totalmessagesreceived; d++)
                        {
                            if (_ReadMessage.ContainsKey(d) == true)
                            {
                                PrintToDebug("Begin Message " + d.ToString(), EnD);
                                string bugmessage = _ReadMessage[d];
                                int strlength = 0;
                                bool isadressed = false;
                                string strname = Name;

                                if (msgpl.IsMessageAdressedToMe("Stratego 4", bugmessage) == true)
                                {
                                    strname = "Stratego 4";
                                    isadressed = true;
                                }
                                if (msgpl.IsMessageAdressedToMe("St4", bugmessage) == true)
                                {
                                    strname = "St4";
                                    isadressed = true;
                                }
                                if (msgpl.IsMessageAdressedToMe(Name, bugmessage) == true)
                                {
                                    strname = Name;
                                    isadressed = true;
                                }

                                s = Random(0, 100);

                                PrintToDebug(bugmessage, EnD);
                                PrintToDebug("MsgState=" + MsgState.ToString(), EnD);

                                if (isadressed == true)
                                {
                                    PrintToDebug("Start Addressed.", EnD);
                                    bugmessage = _ReadMessage[d];
                                    strlength = bugmessage.Length - (strname.Length + 2);
                                    bugmessage = bugmessage.Substring(strname.Length + 2, strlength);
                                    bugmessage = bugmessage.ToLower();

                                    _WordInMessage.Clear();

                                    msgpl.BreakDownMessageIntoWords(bugmessage, _WordInMessage);

                                    PrintToDebug(bugmessage + "  wim=" + _WordInMessage.Count.ToString(), EnD);

                                    if (_SentByPlayer[d].ToLower() == "beat2k")
                                    {
                                        if (bugmessage == "modedebugon")
                                            debuggerenabled = true;
                                        if (bugmessage == "modedebugoff")
                                            debuggerenabled = false;
                                    }

                                    if ((MsgState == 0) & ((bugmessage == "alliance?") | (bugmessage == "ally with me?") | (bugmessage == "do you want to ally with me?") | (bugmessage == "ally?")))
                                    {
                                        PrintToDebug("0 d=" + d.ToString(), EnD);
                                        //if an other player gave me an alliance message
                                        if (_TrustLevel[_SentByPlayer[d]] >= 50)
                                        {
                                            if (playersactive > 2 && alliedplayers < playersactive / 2)
                                            {
                                                if ((closest <= 30) | ((AlliedWithMe(_SentByPlayer[d]) == AllianceLevel.Formal) | (_TrustLevel[_SentByPlayer[d]] > 110)))
                                                {
                                                    SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Yes");
                                                    if (AlliedWithMe(_SentByPlayer[d]) == AllianceLevel.None)
                                                    {
                                                        SetAlliance(_SentByPlayer[d], AllianceLevel.Formal);
                                                        tmpalliancelevel[_SentByPlayer[d]] = AllianceLevel.Formal;
                                                    }
                                                    else
                                                    {
                                                        SetAlliance(_SentByPlayer[d], AlliedWithMe(_SentByPlayer[d]));
                                                        tmpalliancelevel[_SentByPlayer[d]] = AlliedWithMe(_SentByPlayer[d]);
                                                    }
                                                }
                                                else
                                                {
                                                    SendMessage(ChatChannel.All, _SentByPlayer[d] + ", No");
                                                }
                                            }
                                            else
                                            {
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", No");
                                            }
                                        }
                                        else
                                        {
                                            if (s > 50)
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", No");
                                            else
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", No, I don\'t trust you yet.");
                                        }
                                        PrintToDebug("0 d2=" + _SentByPlayer[d], EnD);
                                    }
                                    else if (MsgState == 1)
                                    {
                                        PrintToDebug("1 d=" + d.ToString(), EnD);
                                        //if the other player decides to send me a message.
                                        if (MsgStateName == _SentByPlayer[d])
                                        {
                                            if (msgpl.IsPositive(_WordInMessage[0]) == true)
                                            {
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Alliance Made. Switch to allies channel please.");
                                                SetAlliance(_SentByPlayer[d], AllianceLevel.Formal);
                                                tmpalliancelevel[_SentByPlayer[d]] = AllianceLevel.Formal;
                                                MsgState = 0;
                                            }
                                            else if (msgpl.IsNegative(_WordInMessage[0]) == true)
                                            {
                                                if (s > 50)
                                                    SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Ok, Just let me know when you changed your mind..");
                                                else
                                                    SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Ok, whatever. I won\'t make this offer again.");

                                                MsgState = 2;
                                            }
                                            else if ((bugmessage == "alliance?") | (bugmessage == "ally with me?") | (bugmessage == "do you want to ally with me?") | (bugmessage == "ally?"))
                                            {
                                                if (_TrustLevel[_SentByPlayer[d]] >= 50 && alliedplayers < playersactive / 2)
                                                {
                                                    SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Yes");
                                                    if (AlliedWithMe(_SentByPlayer[d]) == AllianceLevel.None)
                                                    {
                                                        SetAlliance(_SentByPlayer[d], AllianceLevel.Formal);
                                                        tmpalliancelevel[_SentByPlayer[d]] = AllianceLevel.Formal;
                                                    }
                                                    else
                                                    {
                                                        tmpalliancelevel[_SentByPlayer[d]] = AlliedWithMe(_SentByPlayer[d]);
                                                        SetAlliance(_SentByPlayer[d], AlliedWithMe(_SentByPlayer[d]));
                                                    }
                                                    MsgState = 0;
                                                }
                                                else
                                                {
                                                    SendMessage(ChatChannel.All, _SentByPlayer[d] + ", No");
                                                    MsgState = 0;
                                                }
                                            }
                                        }
                                        else if ((bugmessage == "alliance?") | (bugmessage == "ally with me?") | (bugmessage == "do you want to ally with me?") | (bugmessage == "ally?"))
                                        {
                                            if (_TrustLevel[_SentByPlayer[d]] >= 50 && alliedplayers < playersactive / 2)
                                            {
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Yes");
                                                if (AlliedWithMe(_SentByPlayer[d]) == AllianceLevel.None)
                                                {
                                                    SetAlliance(_SentByPlayer[d], AllianceLevel.Formal);
                                                    tmpalliancelevel[_SentByPlayer[d]] = AllianceLevel.Formal;
                                                }
                                                else
                                                {
                                                    tmpalliancelevel[_SentByPlayer[d]] = AlliedWithMe(_SentByPlayer[d]);
                                                    SetAlliance(_SentByPlayer[d], AlliedWithMe(_SentByPlayer[d]));
                                                }
                                                MsgState = 0;
                                            }
                                            else
                                            {
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", No");
                                                MsgState = 0;
                                            }
                                        }
                                    }
                                    else if (MsgState == 2)
                                    {
                                        if ((bugmessage == "alliance?") | (bugmessage == "ally with me?") | (bugmessage == "do you want to ally with me?") | (bugmessage == "ally?"))
                                        {
                                            if ((MsgStateName == _SentByPlayer[d]) & (_TrustLevel[_SentByPlayer[d]] >= 50))
                                            {
                                                //IF other player decides to ally with me after refusing an offer, ally with him.
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Yes");
                                                if (AlliedWithMe(_SentByPlayer[d]) == AllianceLevel.None)
                                                {
                                                    SetAlliance(_SentByPlayer[d], AllianceLevel.Formal);
                                                    tmpalliancelevel[_SentByPlayer[d]] = AllianceLevel.Formal;
                                                }
                                                else
                                                {
                                                    tmpalliancelevel[_SentByPlayer[d]] = AlliedWithMe(_SentByPlayer[d]);
                                                    SetAlliance(_SentByPlayer[d], AlliedWithMe(_SentByPlayer[d]));
                                                }
                                                MsgState = 0;
                                            }
                                            else
                                            {
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", No");
                                            }
                                        }
                                    }
                                    else if (MsgState == 3)
                                    {
                                        if ((_TrustLevel[_SentByPlayer[d]] >= 50) & (alliedplayers < playersactive / 2))
                                        {
                                            if (msgpl.IsPositive(_WordInMessage[0]) == true)
                                            {
                                                SetAlliance(_SentByPlayer[d], AllianceLevel.Formal);
                                                tmpalliancelevel[_SentByPlayer[d]] = AllianceLevel.Formal;
                                                MsgState = 0;
                                            }
                                        }
                                    }
                                    else if (MsgState == 4)
                                    {
                                        if (MsgStateName == _SentByPlayer[d])
                                        {
                                            if (_PlayerOrder.ContainsKey("Conquer" + _SentByPlayer[d]) == false)
                                            {
                                                if (msgpl.IsPositive(_WordInMessage[0]) == true)
                                                {
                                                    //Assign Player Order
                                                    _PlayerOrder.Add("Conquer" + _SentByPlayer[d], _PlayerCapital[_SentByPlayer[d]].Name);
                                                    SendMessage(ChatChannel.Friendly, "Ok, don't let the enemy conquer you first!");
                                                    MsgState = 0;
                                                }
                                                else if (msgpl.IsNegative(_WordInMessage[0]) == true)
                                                {
                                                    SendMessage(ChatChannel.Friendly, "Ok. whatever..");
                                                    MsgState = 0;
                                                }
                                            }
                                            else
                                            {
                                                SendMessage(ChatChannel.Friendly, "I'm already working on it!");
                                            }
                                        }
                                    }
                                    PrintToDebug("End Adressed", EnD);
                                }
                                else
                                {
                                    PrintToDebug("Start Non-Addressed.", EnD);
                                    _WordInMessage.Clear();

                                    bugmessage = _ReadMessage[d];
                                    bugmessage = bugmessage.ToLower();

                                    msgpl.BreakDownMessageIntoWords(bugmessage, _WordInMessage);

                                    PrintToDebug(bugmessage + "  wim=" + _WordInMessage.Count.ToString(), EnD);

                                    if (_SentByPlayer[d].ToLower() == "beat2k")
                                    {
                                        if (bugmessage == "modedebugon")
                                            debuggerenabled = true;
                                        if (bugmessage == "modedebugoff")
                                            debuggerenabled = false;
                                    }

                                    if (MsgState == 0)
                                    {
                                        if ((bugmessage == "alliance?") | (bugmessage == "ally with me?") | (bugmessage == "do you want to ally with me?") | (bugmessage == "ally?") | (bugmessage == "help! someone ally with me?"))
                                        {
                                            if ((MsgStateName == _SentByPlayer[d]) & (_TrustLevel[_SentByPlayer[d]] >= 50) & (alliedplayers < playersactive / 2))
                                            {
                                                //IF other player decides to ally with me after refusing an offer, ally with him.
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Yes");
                                                if (AlliedWithMe(_SentByPlayer[d]) == AllianceLevel.None)
                                                {
                                                    SetAlliance(_SentByPlayer[d], AllianceLevel.Formal);
                                                    tmpalliancelevel[_SentByPlayer[d]] = AllianceLevel.Formal;
                                                }
                                                else
                                                {
                                                    tmpalliancelevel[_SentByPlayer[d]] = AlliedWithMe(_SentByPlayer[d]);
                                                    SetAlliance(_SentByPlayer[d], AlliedWithMe(_SentByPlayer[d]));
                                                }
                                                MsgState = 0;
                                            }
                                            else
                                            {
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", No");
                                            }
                                        }
                                        else if ((bugmessage == "conquer me") | (bugmessage == "take me over") | (bugmessage == "conquer me!") | (bugmessage == "take me over!"))
                                        {
                                            if ((AlliedWithMe(_SentByPlayer[d]) != AllianceLevel.None) & (AlliedWith(_SentByPlayer[d]) != AllianceLevel.None))
                                            {
                                                SendMessage(ChatChannel.Friendly, "Are you sure you want me to conquer you?");
                                                MsgState = 4;
                                                MsgStateName = _SentByPlayer[d];
                                            }
                                        }
                                        else if ((bugmessage == "attack now") | (bugmessage == "attack") | (bugmessage == "attack now!") | (bugmessage == "attack!") |
                                           (bugmessage == "attack now!!") | (bugmessage == "attack!!") | (bugmessage == "attack now!!!") | (bugmessage == "attack!!!"))
                                        {
                                            if ((AlliedWithMe(_SentByPlayer[d]) != AllianceLevel.None) & (AlliedWith(_SentByPlayer[d]) != AllianceLevel.None))
                                            {
                                                if (SE == true)
                                                {
                                                    if (CalAttack == true)
                                                    {
                                                        if (CapitalTask == 1)
                                                        {
                                                            scanshipattack = true;
                                                            SendMessage(ChatChannel.Friendly, "Attack NOW!");
                                                        }
                                                        else
                                                        {
                                                            SendMessage(ChatChannel.Friendly, "The attack is already in progress!");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (CapitalTask == 1)
                                                        {
                                                            closetocapital = true;
                                                            SendMessage(ChatChannel.Friendly, "OK! When my spyship is built, we will head towards the enemy capital.");
                                                        }
                                                        else
                                                        {
                                                            closetocapital = true;
                                                            SendMessage(ChatChannel.Friendly, "OK!");
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    SendMessage(ChatChannel.Friendly, "I don't have a capital to target.");
                                                }
                                            }
                                        }
                                        else if (_WordInMessage.Count == 2)
                                        {
                                            if ((_WordInMessage[0] == "take") | (_WordInMessage[0] == "conquer") | (_WordInMessage[0] == "attack"))
                                            {
                                                tmpstr1 = _WordInMessage[1];
                                                if (FindStarName(tmpstr1) != null)
                                                {
                                                    if ((AlliedWithMe(FindStarName(tmpstr1).Owner) != AllianceLevel.None) & (AlliedWith(FindStarName(tmpstr1).Owner) != AllianceLevel.None))
                                                    {
                                                        if (_PlayerOrder.ContainsKey("Take" + FindStarName(tmpstr1).Name) == false)
                                                        {
                                                            SendMessage(ChatChannel.Friendly, "Ok.");
                                                            _PlayerOrder.Add("Take" + FindStarName(tmpstr1).Name, "Star");
                                                        }
                                                        else
                                                        {
                                                            SendMessage(ChatChannel.Friendly, "You already told me to take that.");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        SendMessage(ChatChannel.Friendly, "I'm already planning on taking that star.");
                                                    }
                                                }
                                                else
                                                {
                                                    SendMessage(ChatChannel.Friendly, "I don't see that star on the map.");
                                                }
                                            }
                                        }
                                        else if (_WordInMessage.Count == 3)
                                        {
                                            if ((_WordInMessage[0] == "capital") & (_WordInMessage[1] == "at"))
                                            {
                                                if ((AlliedWithMe(_SentByPlayer[d]) != AllianceLevel.None) & (AlliedWith(_SentByPlayer[d]) != AllianceLevel.None))
                                                {
                                                    tmpstr1 = _WordInMessage[2];
                                                    if (numcapitals < playersactive)
                                                    {
                                                        if (FindStarName(tmpstr1) != null)
                                                        {
                                                            if (_PlayerOrder.ContainsKey("Cap" + FindStarName(tmpstr1).Name) == false)
                                                            {
                                                                if (_LastStarOwner[FindStarName(tmpstr1).Name] == -1)
                                                                {
                                                                    SendMessage(ChatChannel.Friendly, "Ok.");
                                                                    _PlayerOrder.Add("Cap" + FindStarName(tmpstr1).Name, "Capital");
                                                                    numcapitals++;
                                                                }
                                                                else
                                                                {
                                                                    SendMessage(ChatChannel.Friendly, "That star is not a capital.");
                                                                }
                                                            }
                                                            else
                                                            {
                                                                SendMessage(ChatChannel.Friendly, "I already know that star is a capital.");
                                                            }
                                                        }
                                                        else
                                                        {
                                                            SendMessage(ChatChannel.Friendly, "I don't see that star on the map.");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        SendMessage(ChatChannel.Friendly, "I already know where the capitals are.");
                                                    }
                                                }
                                            }
                                        }
                                        else if (_WordInMessage.Count >= 4)
                                        {
                                            if (((_WordInMessage[1] == "is") & (_WordInMessage[2] == "a") & ((_WordInMessage[3] == "capital") | (_WordInMessage[3] == "capital!") | (_WordInMessage[3] == "capital."))))
                                            {
                                                if ((AlliedWithMe(_SentByPlayer[d]) != AllianceLevel.None) & (AlliedWith(_SentByPlayer[d]) != AllianceLevel.None))
                                                {
                                                    tmpstr1 = _WordInMessage[0];
                                                    if (numcapitals < playersactive)
                                                    {
                                                        if (FindStarName(tmpstr1) != null)
                                                        {
                                                            if (_PlayerOrder.ContainsKey("Cap" + FindStarName(tmpstr1).Name) == false)
                                                            {
                                                                if (_LastStarOwner[FindStarName(tmpstr1).Name] == -1)
                                                                {
                                                                    SendMessage(ChatChannel.Friendly, "Ok.");
                                                                    _PlayerOrder.Add("Cap" + FindStarName(tmpstr1).Name, "Capital");
                                                                    numcapitals++;
                                                                }
                                                                else
                                                                {
                                                                    SendMessage(ChatChannel.Friendly, "That star is not a capital.");
                                                                }
                                                            }
                                                            else
                                                            {
                                                                SendMessage(ChatChannel.Friendly, "I already know that star is a capital.");
                                                            }
                                                        }
                                                        else
                                                        {
                                                            SendMessage(ChatChannel.Friendly, "I don't see that star on the map.");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        SendMessage(ChatChannel.Friendly, "I already know where the capitals are.");
                                                    }
                                                }
                                            }
                                        }

                                    }
                                    else if (MsgState == 1)
                                    {
                                        //if the other player responds and he has not addressed me, assume that he is responding to me.
                                        if (MsgStateName == _SentByPlayer[d])
                                        {
                                            if (msgpl.IsPositive(_WordInMessage[0]) == true)
                                            {
                                                SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Alliance Made. Switch to allies channel please.");
                                                SetAlliance(_SentByPlayer[d], AllianceLevel.Formal);
                                                tmpalliancelevel[_SentByPlayer[d]] = AllianceLevel.Formal;
                                                MsgState = 0;
                                            }
                                            else if (msgpl.IsNegative(_WordInMessage[0]) == true)
                                            {
                                                if (s > 50)
                                                    SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Ok, Just let me know when you changed your mind..");
                                                else
                                                    SendMessage(ChatChannel.All, _SentByPlayer[d] + ", Ok, whatever. I won\'t make this offer again.");

                                                MsgState = 2;
                                            }
                                        }
                                    }
                                    else if (MsgState == 3)
                                    {
                                        if ((_TrustLevel[_SentByPlayer[d]] >= 50) & (alliedplayers < playersactive / 2))
                                        {
                                            if (msgpl.IsPositive(_WordInMessage[0]) == true)
                                            {
                                                SetAlliance(_SentByPlayer[d], AllianceLevel.Formal);
                                                tmpalliancelevel[_SentByPlayer[d]] = AllianceLevel.Formal;
                                                MsgState = 0;
                                            }
                                        }
                                    }
                                    else if (MsgState == 4)
                                    {
                                        if (MsgStateName == _SentByPlayer[d])
                                        {
                                            if (_PlayerOrder.ContainsKey("Conquer" + _SentByPlayer[d]) == false)
                                            {
                                                if (msgpl.IsPositive(_WordInMessage[0]) == true)
                                                {
                                                    //Assign Player Order
                                                    _PlayerOrder.Add("Conquer" + _SentByPlayer[d], _PlayerCapital[_SentByPlayer[d]].Name);
                                                    SendMessage(ChatChannel.Friendly, "Ok, don't let the enemy conquer you first!");
                                                    MsgState = 0;
                                                }
                                                else if (msgpl.IsNegative(_WordInMessage[0]) == true)
                                                {
                                                    SendMessage(ChatChannel.Friendly, "Ok. whatever..");
                                                    MsgState = 0;
                                                }
                                            }
                                            else
                                            {
                                                SendMessage(ChatChannel.Friendly, "I'm already working on it!");
                                            }
                                        }
                                    }
                                    PrintToDebug("End Non-Adressed", EnD);

                                    //taunt
                                    if (_WordInMessage.Count == 1)
                                    {
                                        if ((MsgState == 0) &
                                            ((_WordInMessage[0] == "arg!") | (_WordInMessage[0] == "argh!") |
                                            (_WordInMessage[0] == "nooo") | (_WordInMessage[0] == "nooooo") |
                                            (_WordInMessage[0] == "noooo") | (_WordInMessage[0] == "noooooo") |
                                            (_WordInMessage[0] == "!") | (_WordInMessage[0] == "noooo!") |
                                            (_WordInMessage[0] == "!!") | (_WordInMessage[0] == "!!!") |
                                            (_WordInMessage[0] == "!!!!") | (_WordInMessage[0] == "!!!!!") |
                                            (_WordInMessage[0] == "arg!!") | (_WordInMessage[0] == "argh!!") |
                                            (_WordInMessage[0] == "arg!!!") | (_WordInMessage[0] == "argh!!!") |
                                            (_WordInMessage[0] == "no!") | (_WordInMessage[0] == "noo!") |
                                            (_WordInMessage[0] == "nuts!") | (_WordInMessage[0] == "nuts") |
                                            (_WordInMessage[0] == "drat") | (_WordInMessage[0] == "drat!") |
                                            (_WordInMessage[0] == "ahhh!") | (_WordInMessage[0] == "ahh!") |
                                            (_WordInMessage[0] == "ahhhh!") | (_WordInMessage[0] == "ahhhhh!") |
                                            (_WordInMessage[0] == "grr") | (_WordInMessage[0] == "grrr") |
                                            (_WordInMessage[0] == "grrrr") | (_WordInMessage[0] == "grrrrr") |
                                            (_WordInMessage[0] == "nooo!") | (_WordInMessage[0] == "nooooo!")))
                                        {
                                            if (AlliedWith(_SentByPlayer[d]) == AllianceLevel.None)
                                            {
                                                if (s > 80)
                                                    SendMessage(ChatChannel.All, "HA HA " + _SentByPlayer[d] + "! :D");
                                                else if (s > 60)
                                                    SendMessage(ChatChannel.All, "LOL hahahaha!");
                                                else if (s > 40)
                                                    SendMessage(ChatChannel.All, "Resistance is futile!");
                                                else if (s > 20)
                                                    SendMessage(ChatChannel.All, "Surrender now!");
                                                else
                                                    SendMessage(ChatChannel.All, "Gotcha!");
                                            }
                                            else
                                            {
                                                if (s > 67)
                                                    SendMessage(ChatChannel.Friendly, "What in the world did you just do?");
                                                else if (s > 33)
                                                    SendMessage(ChatChannel.Friendly, "What happened?");
                                                else
                                                    SendMessage(ChatChannel.Friendly, "What did you do now?");
                                            }
                                        }
                                        //
                                    }


                                    if (_WordInMessage.Count >= 2)
                                    {
                                        if ((MsgState == 0) &
                                            (((_WordInMessage[0] == "darn") & (_WordInMessage[1] == "it")) |
                                            ((_WordInMessage[0] == "oh") & (_WordInMessage[1] == "mand")) |
                                            ((_WordInMessage[0] == "oh") & (_WordInMessage[1] == "man")) |
                                            ((_WordInMessage[0] == "oh") & (_WordInMessage[1] == "no!")) |
                                            ((_WordInMessage[0] == "oh") & (_WordInMessage[1] == "noo!")) |
                                            ((_WordInMessage[0] == "oh") & (_WordInMessage[1] == "nooo!")) |
                                            ((_WordInMessage[0] == "oh") & (_WordInMessage[1] == "noooo!")) |
                                            ((_WordInMessage[0] == "oh") & (_WordInMessage[1] == "nooooo!")) |
                                            ((_WordInMessage[0] == "dang") & (_WordInMessage[1] == "it")) |
                                            ((_WordInMessage[0] == "oh") & (_WordInMessage[1] == "no")) |
                                            ((_WordInMessage[0] == "damn") & (_WordInMessage[1] == "you"))))
                                        {
                                            if (AlliedWith(_SentByPlayer[d]) == AllianceLevel.None)
                                            {
                                                if (s > 80)
                                                    SendMessage(ChatChannel.All, "HA HA " + _SentByPlayer[d] + "! :D");
                                                else if (s > 60)
                                                    SendMessage(ChatChannel.All, "LOL hahahaha!");
                                                else if (s > 40)
                                                    SendMessage(ChatChannel.All, "Resistance is futile!");
                                                else if (s > 20)
                                                    SendMessage(ChatChannel.All, "Surrender now!");
                                                else
                                                    SendMessage(ChatChannel.All, "Gotcha!");
                                            }
                                            else
                                            {
                                                if (s > 67)
                                                    SendMessage(ChatChannel.Friendly, "What in the world did you just do?");
                                                else if (s > 33)
                                                    SendMessage(ChatChannel.Friendly, "What happened?");
                                                else
                                                    SendMessage(ChatChannel.Friendly, "What did you do now?");
                                            }
                                        }
                                        if ((MsgState == 0) &
                                           (((_WordInMessage[0] == "surrender") & (_WordInMessage[1] == "now")) |
                                            ((_WordInMessage[0] == "surrender") & (_WordInMessage[1] == "now!")) |
                                            ((_WordInMessage[0] == "forfeit") & (_WordInMessage[1] == "the")) |
                                            ((_WordInMessage[0] == "give") & (_WordInMessage[1] == "it")) |
                                            ((_WordInMessage[0] == "give") & (_WordInMessage[1] == "up,")) |
                                            ((_WordInMessage[0] == "give") & (_WordInMessage[1] == "up"))))
                                        {
                                            if (AlliedWith(_SentByPlayer[d]) == AllianceLevel.None)
                                            {
                                                if (s > 80)
                                                    SendMessage(ChatChannel.All, "NEVER! :D");
                                                else if (s > 60)
                                                    SendMessage(ChatChannel.All, "You will never beat me!");
                                                else if (s > 40)
                                                    SendMessage(ChatChannel.All, "I will never surrender to you!");
                                                else if (s > 20)
                                                    SendMessage(ChatChannel.All, "No, you surrender now! :D");
                                                else
                                                    SendMessage(ChatChannel.All, "LOL!");
                                            }
                                        }

                                        PrintToDebug("EndTaunts", EnD);
                                        //
                                    }
                                }
                                PrintToDebug("End Message", EnD);
                            }
                        }
                    }

                    //StarSystemInfo testerror = null;
                    //if (testerror.Owner == "ERROR!")
                    //{
                        //ERROR TEST!!!!
                    //}
                    #endregion

                    //Gather Intelligence from StarShips
                    PrintToDebug("--------StarShip Intelligence--------", EnD);

                    #region StarShip Intelligence
                    //Process the known enemy locations of starships. 
                    //Remove the locations eventually if there is no longer any activity.
                    int removedpts = 0;
                    int endpts = 0;
                    Point[] removedpt = new Point[32768];
                    Point[] endpt = new Point[32768];
                    StoredEnemyLocations = _EnemyIntensity.Count;
                    if (StoredEnemyLocations > 0)
                    {
                        //read each entry into Enemy Intensity field
                        foreach (Point enp in _EnemyIntensity.Keys)
                        {
                            if ((_EnemyIntensity[enp] <= 0) | (Distance((int)enp.X,(int)enp.Y,mycapx,mycapy) <= (TechMultiple * 1.5) + 10))
                            {
                                removedpts++;
                                removedpt[removedpts - 1] = enp;
                            }
                            else
                            {
                                endpts++;
                                endpt[endpts - 1] = enp;
                            }
                        }
                        //remove any that timed out (value <= 0)
                        for (int d = 0; d < removedpts; d++)
                        {
                            _EnemyIntensity.Remove(removedpt[d]);
                            _DronesToThis.Remove(removedpt[d]);
                        }
                        //decrease the value of the field by 1 (value > 0)
                        for (int d = 0; d < endpts; d++)
                        {
                            _EnemyIntensity[endpt[d]] = _EnemyIntensity[endpt[d]] - (int)((_EnemyIntensity[endpt[d]] / 25) + 1);
                            _DronesToThis[endpt[d]] = 0;
                        }
                    }
                    LargeEnemies = 0;
                    _LargeEnemy.Clear();
                    int[] intBS = new int[Ships + 1];
                    int[] intenemyship = new int[Ships + 1];
                    int[] intalliedship = new int[Ships + 1];
                    int[] intvisship = new int[Ships + 1];
                    int Alliedships = 0;
                    int DefendWarships = 0;
                    int AttackWarships = 0;
                    int SearchWarships = 0;
                    int CavalryWarships = 0;
                    int WarshipsReady = 0;
                    int WarshipListIndex = _WarShipList.Count;
                    int totalenemycloakedunits = 0;
                    int VisibleShips = 0;
                    int EWarships = 0;
                    int TotalAttackStrength = 0;
                    int EnemyShips = 0;
                    int AvgAttackStrength = 0;
                    bool CDAlert = false;
                    int TSs = 0;
                    int SSs = 0;
                    int STs = 0;
                    int RSs = 0;
                    int CDs = 0;
                    int CSs = 0;
                    int BSs = 0;
                    int MSs = 0;
                    int SGs = 0;
                    int EMs = 0;
                    int ESs = 0;
                    int HJs = 0;
                    int MBs = 0;
                    int RVs = 0;
                    int PSs = 0;
                    int minwarshipwpn = 4;
                    int EnemyMBS = 0;
                    bool enemyupgrade = false;
                    StarShipInfo[] EnemyMB = new StarShipInfo[Ships + 1];
                    StarShipInfo[] CloakDet = new StarShipInfo[Ships + 1];
                    StarShipInfo[] BS = new StarShipInfo[Ships + 1];
                    StarShipInfo ParentScanship = null;
                    StarSystemInfo tmpsys = null;
                    BS[Ships] = null;
                    int SpyOrderX = -1;
                    string shipcode;
                    int SpyOrderY = -1;
                    int AlertPriority = 0;
                    double closestdist = 36767.9;
                    double MinSTDist = 36767.9;
                    bool damagealert = false;
                    int cloakedSSs = 0;
                    int ad = -1;
                    double floArcdist = 32767.9;
                    int defendwpn = ewpn + 1;
                    int cavalrywpn = ewpn + 4;
                    int tmpdefendwpn = ewpn + 1;
                    int tmpcavalrywpn = ewpn + 4;
                    if (defendwpn > (TechMultiple * 2) + 5)
                    {
                        defendwpn = (int)((TechMultiple * 2) + 5);
                        cavalrywpn = (int)((TechMultiple * 2) + 8);
                    }
                    double caldist = 0;
                    if (InitMaxSTRange == false)
                    {
                        InitMaxSTRange = true;
                        i = 0;
                        while (i <= 10)
                        {
                            MaxSTRange[i] = -1;
                            i = i + 1;
                        }
                        i = 0;
                    }
                    s = 0;
                    foreach (StarShipInfo ship in StarShips)
                    {
                        if ((ship.ShipType == StarShipType.BeamShip) | (ship.ShipType == StarShipType.CloakDetector) |
                           (ship.ShipType == StarShipType.CommandShip) | (ship.ShipType == StarShipType.RepairShip) |
                           (ship.ShipType == StarShipType.ScanShip) | (ship.ShipType == StarShipType.SpyShip) |
                           (ship.ShipType == StarShipType.StarTillery) | (ship.ShipType == StarShipType.ParalyShip))
                        {
                            if ((ship.IsDamaged == true) & (ship.OwnedByMe == true))
                                damagealert = true;
                            if ((CapitalTask == 1) & (ship.OwnedByMe == true) & (ParentScanship == null))
                                if ((ship.Cloaked == true) & (ship.Value >= 15) & (ship.ShipType == StarShipType.SpyShip))
                                    ParentScanship = ship;
                        }
                        if ((ship.OwnedByMe == true) | ((AlliedWithMe(ship.Owner) != AllianceLevel.None) &
                            ((ship.ShipType == StarShipType.WarShip) | (ship.ShipType == StarShipType.DoppleShip) | (ship.ShipType == StarShipType.Elite))))
                        {
                            if ((ship.ShipType == StarShipType.WarShip) | (ship.ShipType == StarShipType.DoppleShip) | (ship.ShipType == StarShipType.Elite))
                            {
                                if (_shipTask.ContainsKey(ship.Code) == true)
                                {
                                    //if the warship is assigned, assume it is owned by me.
                                    if ((_shipTask[ship.Code] == 4) & (SE == true))
                                    {
                                        CavalryWarships++;
                                        if ((CapitalTask == 1) & (ship.Engines >= 18))
                                        {
                                            EWarships = EWarships + 1;
                                            EWarship[EWarships - 1] = ship;
                                            TotalAttackStrength = TotalAttackStrength + ship.Value;
                                        }
                                        if ((ship.X >= mycapx - 20) & (ship.Y >= mycapy - 20) & (ship.X <= mycapx + 20) & (ship.Y <= mycapy + 20))
                                            WarshipsReady = WarshipsReady + 1;
                                        caldist = DistanceQuick(ship.X, ship.Y, Ecapx, Ecapy);
                                        if (caldist < CApp)
                                            CApp = caldist;
                                    }
                                }
                                else if ((SE == true) & (ship.Value >= cavalrywpn))
                                {
                                    //else if the warship has not yet been assigned, or the warship is owned by an ally
                                    CavalryWarships++;
                                    if ((CapitalTask == 1) & (ship.Engines >= 18))
                                    {
                                        EWarships = EWarships + 1;
                                        EWarship[EWarships - 1] = ship;
                                        TotalAttackStrength = TotalAttackStrength + ship.Value;
                                    }
                                    if ((ship.X >= mycapx - 20) & (ship.Y >= mycapy - 20) & (ship.X <= mycapx + 20) & (ship.Y <= mycapy + 20))
                                        WarshipsReady = WarshipsReady + 1;
                                    caldist = DistanceQuick(ship.X, ship.Y, Ecapx, Ecapy);
                                    if (caldist < CApp)
                                        CApp = caldist;
                                }
                                if (ship.OwnedByMe == true)
                                {
                                    //count only my warships! for organization reasons only!
                                    if ((ship.Value >= defendwpn) & ((ship.Value < cavalrywpn) | (SE == false)))
                                    {
                                        DefendWarships++;
                                    }
                                    else if (ship.Value < defendwpn)
                                    {
                                        AttackWarships++;
                                        if ((AttackWarships > SearchWarships * 5) & (SearchWarships < unknowns / 4) & (AttackWarships > 5))
                                        {
                                            AttackWarships--;
                                            SearchWarships++;
                                        }
                                    }
                                }
                                //See how many warships are targeted to a star.
                                shipcode = ship.Code;
                                if (_shipTask.ContainsKey(ship.Code) == true)
                                {
                                    if (_shipTask[ship.Code] == 2)
                                    {
                                        _WarShipList.Add(WarshipListIndex, ship);
                                        WarshipListIndex++;
                                        if (_shipTargetOrder.ContainsKey(ship.Code) == true)
                                        {
                                            _TAValue[_shipTargetOrder[ship.Code].Name] = _TAValue[_shipTargetOrder[ship.Code].Name] + ship.Value;
                                        }
                                    }
                                    if (_shipTask[ship.Code] == 1)
                                    {
                                        _WarShipList.Add(WarshipListIndex, ship);
                                        WarshipListIndex++;
                                        if (_shipTargetOrder.ContainsKey(ship.Code) == true)
                                        {
                                            tmpsys = _shipTargetOrder[ship.Code];
                                            if (tmpsys != null)
                                                if (Distance(tmpsys.X, tmpsys.Y, ship.X, ship.Y) <= (ship.Engines / 1.6))
                                                    _WarshipWeaponsNearStar[tmpsys.Name] = _WarshipWeaponsNearStar[tmpsys.Name] + ship.Value;
                                        }
                                    }
                                }
                            }
                            //Process ships only owned by me
                            if (ship.OwnedByMe == true)
                            {
                                if (ship.ShipType == StarShipType.TechShip)
                                    TSs = TSs + 1;
                                if ((ship.ShipType == StarShipType.ScanShip) | (ship.ShipType == StarShipType.SpyShip))
                                {
                                    SSs = SSs + 1;
                                    if ((ship.Cloaked == true) & (ship.Engines >= 10) & (ship.Value >= 10))
                                        cloakedSSs = cloakedSSs + 1;
                                    if ((ship.Value >= 5) & (ParentScanship != ship))
                                    {
                                        i = 0;
                                        while (i < mystars)
                                        {
                                            ssi = mystar[i];
                                            mx = Math.Abs(ssi.X - ship.X);
                                            my = Math.Abs(ssi.Y - ship.Y);
                                            mx = mx * mx;
                                            my = my * my;
                                            floArcdist = Math.Sqrt(mx + my);
                                            if (floArcdist <= ship.Value - 5)
                                            {
                                                _StarCovered[ssi.Name] = true;
                                            }
                                            i = i + 1;
                                        }
                                    }
                                }
                                if (ship.ShipType == StarShipType.RepairShip)
                                    RSs = RSs + 1;
                                //the role of the cloakdetector is to patrol the perimeter of the capital and alert if there are cloaked starships nearby.
                                if (ship.ShipType == StarShipType.CloakDetector)
                                {
                                    CDs = CDs + 1;
                                    CloakDet[CDs - 1] = ship;
                                    if (ship.CloakArrows.Count > 0)
                                    {
                                        totalenemycloakedunits = totalenemycloakedunits + ship.CloakArrows.Count;
                                        CDAlert = true;
                                    }
                                }
                                if (ship.ShipType == StarShipType.ParalyShip)
                                    PSs = PSs + 1;
                                if (ship.ShipType == StarShipType.RemoteViewer)
                                    RVs = RVs + 1;
                                if (ship.ShipType == StarShipType.CommandShip)
                                    CSs = CSs + 1;
                                if (ship.ShipType == StarShipType.EMine)
                                    EMs = EMs + 1;
                                if (ship.ShipType == StarShipType.MineSweeper)
                                    ESs = ESs + 1;
                                if (ship.ShipType == StarShipType.HijackShip)
                                    HJs = HJs + 1;
                                if (ship.ShipType == StarShipType.BeamShip)
                                    MSs = MSs + 1;
                                if (ship.ShipType == StarShipType.ShieldGenerator)
                                    SGs = SGs + 1;
                                if (ship.ShipType == StarShipType.MadBomb)
                                    MBs = MBs + 1;
                                if (ship.ShipType == StarShipType.BattleStation)
                                {
                                    BSs = BSs + 1;
                                    BS[BSs - 1] = ship;
                                    intBS[BSs - 1] = s;
                                    if (_BattleStationSlots.ContainsKey(ship.Code) == false)
                                        _BattleStationSlots.Add(ship.Code, 0);
                                    else
                                        _BattleStationSlots[ship.Code] = 0;
                                }
                                if (ship.ShipType == StarShipType.StarTillery)
                                {
                                    caldist = Distance(ship.X, ship.Y, mycapx, mycapy);
                                    if (MinSTDist > caldist)
                                        MinSTDist = caldist;
                                    STs = STs + 1;
                                }

                                //trigger the attack signal if one of my starships gets close enough to the capital.
                                if (SE == true)
                                {
                                    if (Distance(ship.X, ship.Y, Ecapx, Ecapy) <= ((TechMultiple / 4) + 2.75))
                                        closetocapital = true;
                                }
                            }
                        }
                        else if ((AlliedWith(ship.Owner) == AllianceLevel.None) | (AlliedWithMe(ship.Owner) == AllianceLevel.None))
                        {
                            if (_EnemyHasMines.ContainsKey(ship.Owner) == false)
                                _EnemyHasMines.Add(ship.Owner, false);

                            EnemyShips = EnemyShips + 1;
                            enemyship[EnemyShips - 1] = ship;
                            intenemyship[EnemyShips - 1] = s;
                            VisibleShips = VisibleShips + 1;
                            visship[VisibleShips - 1] = ship;
                            intvisship[VisibleShips - 1] = s;
                            if (EnemySighted == false)
                                EnemySighted = true;
                            if ((ship.IdentifiedByMe == false) | (ship.ShipType == StarShipType.WarShip) | (ship.ShipType == StarShipType.Elite))
                            {
                                if ((ship.MaxValue > 0) | (ship.KnownWeapons > 0))
                                {
                                    if ((ship.Value < tmpdefendwpn) | (ship.KnownWeapons < tmpdefendwpn))
                                    {
                                        if ((ship.KnownWeapons > 3) & (minewpn > ship.KnownWeapons))
                                            minewpn = ship.KnownWeapons;
                                        else if ((minewpn > ship.MaxValue))
                                            minewpn = ship.Value;
                                    }
                                    if ((ship.Value >= tmpdefendwpn) | (ship.KnownWeapons >= tmpdefendwpn))
                                    {
                                        if (ship.KnownWeapons >= tmpdefendwpn) ewpn = ship.KnownWeapons + Random(1, 3);
                                        else if (ship.MaxValue >= tmpdefendwpn) ewpn = ship.MaxValue + Random(1, 3);
                                        if ((alliedcheck == true) & (enemyupgrade == false))
                                        {
                                            enemyupgrade = true;
                                            SendMessage(ChatChannel.Friendly, "The enemy has built bigger warships! Upgrade your weapons immediately!");
                                        }
                                    }
                                }
                            }
                            if ((ship.IdentifiedByMe == true) & (ship.ShipType == StarShipType.MadBomb))
                            {
                                EnemyMBS++;
                                EnemyMB[EnemyMBS - 1] = ship;
                            }
                            if ((mycapx - (4 + TechMultiple) <= ship.X) & (mycapy - (4 + TechMultiple) <= ship.Y) &
                                (mycapx + (4 + TechMultiple) >= ship.X) & (mycapy + (4 + TechMultiple) >= ship.Y))
                            {
                                if ((ship.IdentifiedByMe == false) | (ship.ShipType == StarShipType.WarShip) | (ship.ShipType == StarShipType.Elite))
                                {
                                    if (ship.Value > 0)
                                        AlertPriority = AlertPriority + ship.Value;
                                    else if (ship.KnownWeapons > 0)
                                        AlertPriority = AlertPriority + ship.KnownWeapons;
                                    else
                                        AlertPriority = AlertPriority + 8;
                                }
                            }
                            if (ship.ShipType == StarShipType.StarTillery)
                            {
                                if (MaxSTRange[ship.OwnerInt] < ship.Value)
                                    MaxSTRange[ship.OwnerInt] = ship.Value;
                                TEStartillery = true;
                                PlayerHasStartillery[ship.OwnerInt] = true;
                            }
                            if (ship.ShipType == StarShipType.EMine)
                            {
                                _EnemyHasMines[ship.Owner] = true;
                            }

                            if (ship.IdentifiedByMe == true)
                            {
                                if (ship.MaxEngines * ship.MaxValue >= ((TechMultiple * 25) + 75))
                                {
                                    LargeEnemies++;
                                    _LargeEnemy.Add(LargeEnemies - 1, ship);
                                }
                            }
                            else
                            {
                                if (ship.KnownWeapons > (TechMultiple + 6))
                                {
                                    LargeEnemies++;
                                    _LargeEnemy.Add(LargeEnemies - 1, ship);
                                }      
                            }

                            //store the location of the enemy starship
                            Point curpoint = new Point(ship.X, ship.Y);
                            StoredEnemyLocations = _EnemyIntensity.Count;
                            if (StoredEnemyLocations == 0)
                            {
                                if (ship.IdentifiedByMe == false)
                                {
                                   _EnemyIntensity.Add(curpoint, 25);
                                   _DronesToThis.Add(curpoint, 0);
                                }
                                else
                                {
                                   _EnemyIntensity.Add(curpoint, (ship.MaxEngines + 1) * (ship.MaxValue + 1));
                                   _DronesToThis.Add(curpoint, 0);
                                }
                            }
                            else
                            {
                                if (_EnemyIntensity.ContainsKey(curpoint) == false)
                                {
                                    if (ship.IdentifiedByMe == false)
                                    {
                                        _EnemyIntensity.Add(curpoint, 25);
                                        _DronesToThis.Add(curpoint, 0);
                                    }
                                    else
                                    {
                                        _EnemyIntensity.Add(curpoint, (ship.MaxEngines + 1) * (ship.MaxValue + 1));
                                        _DronesToThis.Add(curpoint, 0);
                                    }
                                }
                                else
                                {
                                    if (ship.IdentifiedByMe == false)
                                        _EnemyIntensity[curpoint] = _EnemyIntensity[curpoint] + 25;
                                    else
                                        _EnemyIntensity[curpoint] = _EnemyIntensity[curpoint] + ((ship.MaxEngines + 1) * (ship.MaxValue + 1));
                                }
                            }

                            if (ship.Cloaked == true)
                                totalenemycloakedunits++;
                        }
                        else if ((AlliedWith(ship.Owner) != AllianceLevel.None) & (AlliedWithMe(ship.Owner) != AllianceLevel.None))
                        {
                            //If alliance partner has repair capability, use it.
                            if (_EnemyHasMines.ContainsKey(ship.Owner) == false)
                                _EnemyHasMines.Add(ship.Owner, false);

                            if (ship.ShipType == StarShipType.RepairShip)
                            {
                                RSs = RSs + 1;
                            }
                            if (ship.ShipType == StarShipType.BattleStation)
                            {
                                BSs = BSs + 1;
                                BS[BSs - 1] = ship;
                                intBS[BSs - 1] = s;
                                if (_BattleStationSlots.ContainsKey(ship.Code) == false)
                                    _BattleStationSlots.Add(ship.Code, 0);
                                else
                                    _BattleStationSlots[ship.Code] = 0;
                            }

                            Alliedships = Alliedships + 1;
                            alliedship[Alliedships - 1] = ship;
                            intalliedship[Alliedships - 1] = s;

                            if (ship.ShipType == StarShipType.StarTillery)
                            {
                                if (MaxSTRange[ship.OwnerInt] < ship.Value)
                                    MaxSTRange[ship.OwnerInt] = ship.Value;
                                PlayerHasStartillery[ship.OwnerInt] = true;

                                caldist = Distance(ship.X, ship.Y, mycapx, mycapy);
                                if (MinSTDist > caldist)
                                {
                                    MinSTDist = caldist;
                                    _TrustLevel[ship.Owner] = _TrustLevel[ship.Owner] * 1.001;
                                }
                            }

                            //trigger the attack signal if a friendly starship gets close enough to the capital.
                            if (SE == true)
                            {
                                if (Distance(ship.X, ship.Y, Ecapx, Ecapy) <= ((TechMultiple / 4) + 2.75))
                                    closetocapital = true;
                            }
                        }

                        s = s + 1;
                    }
                    s = 0;

                    //if more units are cloaked than uncloaked means the oppponent is cloaking his fleet.
                    if (totalenemycloakedunits >= (EnemyShips / 2) - totalenemycloakedunits)
                        CloakedOpponent = true;

                    StoredEnemyLocations = _EnemyIntensity.Count;

                    int ad1 = 0;
                    int ad2 = 0;
                    int ad3 = 0;
                    //subtract Tshields value if the search warships decide to take that star
                    foreach (StarShipInfo ship in MyStarShips)
                    {
                        if ((ship.ShipType == StarShipType.WarShip) | (ship.ShipType == StarShipType.DoppleShip) | (ship.ShipType == StarShipType.Elite))
                        {
                            shipcode = ship.Code;
                            if (_shipTask.ContainsKey(ship.Code) == true)
                            {
                                if (_shipTask[ship.Code] == 2)
                                {
                                    if (_shipTargetOrder.ContainsKey(ship.Code) == true)
                                    {
                                        stari = _shipTargetOrder[ship.Code];
                                        if (stari.Visible == true)
                                        {
                                            ad1 = ship.Engines + (int)(ship.Value * 1.5);
                                            ad2 = Convert.ToInt32(stari.Value + (stari.Resources / 1.5) + (stari.Scanners / 5));
                                            ad3 = _TShields[stari.Name];
                                            if ((_TAValue[stari.Name] > ad3) & (ad1 <= ad2))
                                            {
                                                if ((AlliedWith(stari.Owner) != AllianceLevel.None) |
                                                    (AlliedWithMe(stari.Owner) != AllianceLevel.None))
                                                {
                                                    //do nothing
                                                }
                                                else
                                                {
                                                    _TShields[stari.Name] = -999;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    PrintToDebug("Warship - Star System Intelligence", EnD);
                    //Process StarSystem Intelligence from warships
                    StarShipInfo wsi;
                    Dictionary<int, StarShipInfo> tmpwarshiplist = new Dictionary<int, StarShipInfo>();
                    int tmpwarindex = 0;
                    int destroyedcount = 0;
                    for (int d = 0; d < _WarShipList.Count; d++)
                    {
                        wsi = _WarShipList[d];
                        if (FindStarShip(wsi.Code) == null)
                        {
                            //this warship is destroyed. See if the target is mine if it has a valid one.
                            if (_shipTargetOrder.ContainsKey(wsi.Code) == true)
                            {
                                stari = _shipTargetOrder[wsi.Code];
                                if (stari != null)
                                {
                                    if (stari.OwnedByMe == false)
                                        PrintToDebug("Warship " + wsi.Code + " is destroyed while targeting " + stari.Name, EnD);
                                    else
                                        PrintToDebug("Warship " + wsi.Code + " is destroyed.", EnD);
                                }
                                if (_shipTask.ContainsKey(wsi.Code) == true)
                                {
                                    if ((_shipTask[wsi.Code] == 1) | (_shipTask[wsi.Code] == 2))
                                        if (stari != null)
                                            if (stari.OwnedByMe == false) //The target is not owned by me so flag it as a conquered star.
                                            {
                                                if (_LastStarOwner[stari.Name] <= 0)
                                                    _LastStarOwner[stari.Name] = 1;
                                                //Increase the attack counter by 1 for every warship that hits this enemy star.
                                                if (_LastStarOwner[stari.Name] == 1)
                                                    _GetStarAttacks[stari.Name]++;
                                            }
                                    //remove task order entry since it is no longer needed
                                    _shipTask.Remove(wsi.Code);
                                }
                                //remove target order entry since it is no longer needed
                                _shipTargetOrder.Remove(wsi.Code);
                            }
                            destroyedcount++;
                        }
                        else
                        {
                            tmpwarshiplist.Add(tmpwarindex, wsi);
                            tmpwarindex++;
                        }
                    }
                    //Rebuild Warship List
                    _WarShipList.Clear();
                    PrintToDebug("AttackWarshipsDestroyed=" + destroyedcount.ToString() + " AttackWarshipsActive=" + tmpwarindex.ToString(), EnD);
                    for (int d = 0; d < tmpwarshiplist.Count; d++)
                    {
                        _WarShipList.Add(d, tmpwarshiplist[d]);
                    }
                    tmpwarshiplist.Clear();

                    for (int d = 0; d < playersactive; d++)
                    {
                        tmpstrplay = PlayerNames[d];
                        if (tmpalliancelevel[tmpstrplay] == AllianceLevel.None)
                        {
                            PrintToDebug(tmpstrplay + ": ta=" + tmpalliancelevel[tmpstrplay].ToString() + " ifa=" + IsFullyAllied(tmpstrplay).ToString(), EnD);
                            PrintToDebug("StarShip Early Alliance", EnD);
                            if ((EnemyShips > 0) & (impulsetime <= 51) & (playersactive > 2) & (alliedplayers < (playersactive / 2)))
                            {
                                s = Random(1, 100);
                                for (int dd = 0; dd < EnemyShips; dd++)
                                {
                                    if (tmpalliancelevel[enemyship[dd].Owner] == AllianceLevel.None && IsFullyAllied(enemyship[dd].Owner) == false)
                                    {
                                        if (_TrustLevel[enemyship[dd].Owner] >= 90)
                                            tmpalliancelevel[enemyship[dd].Owner] = AllianceLevel.Formal;
                                        else if (_TrustLevel[enemyship[dd].Owner] >= 75)
                                            tmpalliancelevel[enemyship[dd].Owner] = AllianceLevel.Visibility;
                                        else if (_TrustLevel[enemyship[dd].Owner] >= 45)
                                            tmpalliancelevel[enemyship[dd].Owner] = AllianceLevel.NonAggression;
                                    }
                                }
                            }
                            PrintToDebug("StarSystem Early Alliance", EnD);
                            if ((visiblestars > 0) & (impulsetime <= 51) & (playersactive > 2) & (alliedplayers < (playersactive / 2)))
                            {
                                for (int dd = 0; dd < visiblestars; dd++)
                                {
                                    if (tmpalliancelevel.ContainsKey(visstar[dd].Owner) == true)
                                    {
                                        if (tmpalliancelevel[visstar[dd].Owner] == AllianceLevel.None && IsFullyAllied(visstar[dd].Owner) == false)
                                        {
                                            if (_TrustLevel[visstar[dd].Owner] >= 90)
                                                tmpalliancelevel[visstar[dd].Owner] = AllianceLevel.Formal;
                                            else if (_TrustLevel[visstar[dd].Owner] >= 75)
                                                tmpalliancelevel[visstar[dd].Owner] = AllianceLevel.Visibility;
                                            else if (_TrustLevel[visstar[dd].Owner] >= 45)
                                                tmpalliancelevel[visstar[dd].Owner] = AllianceLevel.NonAggression;
                                        }
                                    }
                                }
                            }
                            if (tmpalliancelevel.ContainsKey(tmpstrplay) == true)
                            {
                                if ((tmpalliancelevel[tmpstrplay] != AllianceLevel.None) & (IsFullyAllied(tmpstrplay) == false) & (MsgState == 0))
                                {
                                    if ((tmpalliancelevel[tmpstrplay] == AllianceLevel.Visibility) | (tmpalliancelevel[tmpstrplay] == AllianceLevel.Formal))
                                    {
                                        if (s > 67)
                                            SendMessage(ChatChannel.All, tmpstrplay + ", Alliance?");
                                        else if (s > 33)
                                            SendMessage(ChatChannel.All, tmpstrplay + ", Do you want to ally with me?");
                                        else
                                            SendMessage(ChatChannel.All, tmpstrplay + ", Ally with me?");
                                        MsgState = 1;
                                    }
                                    SetAlliance(tmpstrplay, tmpalliancelevel[tmpstrplay]);
                                }
                            }
                        }
                    }

                    PrintToDebug("MyShips=" + MyStarShips.Count.ToString() + " EnemyShips=" + EnemyShips.ToString() + " AlliedShips=" + Alliedships.ToString() + " AlliedPlayers=" + alliedplayers.ToString() + " CDAlert=" + CDAlert.ToString(), EnD);
                    PrintToDebug("SearchWarships=" + SearchWarships.ToString() + " AttackWarships=" + AttackWarships.ToString() + " DefendWarships=" + DefendWarships.ToString() + " CavalryWarships=" + CavalryWarships.ToString(), EnD);
                    PrintToDebug("STs=" + STs.ToString() + " SSs=" + SSs.ToString() + " RSs=" + RSs.ToString() + " CSs=" + CSs.ToString() + " CDs=" + CDs.ToString() + " MSs=" + MSs.ToString(), EnD);
                    PrintToDebug("SGs=" + SGs.ToString() + " ESs=" + ESs.ToString() + " EMs=" + EMs.ToString() + " HJs=" + HJs.ToString() + " BSs=" + BSs.ToString() + " MBs=" + MBs.ToString(), EnD);
                    PrintToDebug("StoredEnemyLocations=" + StoredEnemyLocations.ToString() + " CloseToCapital=" + closetocapital.ToString() + " CloakedEnemy=" + CloakedOpponent.ToString() + " CalAttacks=" + calattacks.ToString(), EnD);

                    #endregion

                    PrintToDebug("--------Cavalry Management--------", EnD);

                    #region Cavalry Management
                    if (firstSee == false && SE == true)
                        calattacks = 1;
                    firstSee = true;

                    if (STs == 0)
                        MinSTDist = 4 + TechMultiple;
                    if (EWarships > 0)
                        AvgAttackStrength = Convert.ToInt32(Math.Round(Convert.ToDouble(TotalAttackStrength / EWarships)));

                    int attackcount = 0;
                    bool BattleStationRepairMode = false;
                    if (damagealert == true)
                        BattleStationRepairMode = true;
                    defendwpn = ewpn + 1;
                    cavalrywpn = ewpn + 4;
                    if (defendwpn > (TechMultiple * 2) + 5)
                    {
                        defendwpn = (int)((TechMultiple * 2) + 5);
                        cavalrywpn = (int)((TechMultiple * 2) + 8);
                    }
                    if ((minewpn >= 3) & (minewpn <= (TechMultiple * 2) + 4))
                        minwarshipwpn = minewpn;
                    else if (minewpn > (int)TechMultiple + 4)
                        minwarshipwpn = 4;
                    else if (minewpn <= 2) 
                        minwarshipwpn = 4;

                    if (calattacks > TechMultiple * 12)
                    {
                        calattacks = (int)(TechMultiple * 12);
                        //debuggerenabled = true;
                    }
                    attackcount = calattacks;
                    if (SE == false)
                        waittime = 50;
                    else
                        waittime--;

                    if (waittime < 50)
                    {
                        PrintToDebug("Time Left x10=" + waittime.ToString(), EnD);
                        if (waittime <= 0 && CavalryWarships <= attackcount / 10)
                            waittime = 10;
                    }

                    PrintToDebug("Capital Task", EnD);
                    if (CapitalTask == 0)
                    {
                        if ((WarshipsReady >= attackcount) | ((closetocapital == true) & (WarshipsReady > attackcount / 4)) | (waittime <= 0))
                        {
                            if ((alliedcheck == true) & (CalAttack == false))
                                SendMessage(ChatChannel.Friendly, "Everyone! Attack the enemy capital NOW!");
                            CalAttack = true;
                            PrintToDebug("ATTACK NOW!", EnD);
                            waittime = 50;
                        }
                    }
                    else
                    {
                        if (ParentScanship == null)
                            CalAttack = false;
                        waittime = 51;
                        if (attackcount <= 2) attackcount = attackcount + 3;
                        if (((WarshipsReady >= attackcount) | ((closetocapital == true) & (WarshipsReady > attackcount / 4))) & (ParentScanship != null))
                        {
                            if ((mycapx - 6 <= ParentScanship.X) & (mycapy - 6 <= ParentScanship.Y) &
                                (mycapx + 6 >= ParentScanship.X) & (mycapy + 6 >= ParentScanship.Y))
                            {
                                CalAttack = true;
                                if (alliedcheck == true)
                                    SendMessage(ChatChannel.Friendly, "Everyone! Follow my spyship " + ParentScanship.Code + " until I say ATTACK!");
                                PrintToDebug("FOLLOW MY SPYSHIP!", EnD);
                            }
                        }
                    }
                    if ((SE == true) & (currecaptar == ""))
                    {
                        currecaptar = Ecap.Name;
                        oldecap = Ecap;
                    }
                    PrintToDebug("Fault Points", EnD);

                    if (((CavalryWarships <= attackcount / 10) & (closetocapital == false)) & (CalAttack == true))
                    {
                        CalAttack = false;
                        calattacks = calattacks + (int)Math.Round(attackcount * (1.5 + (CApp / 8)));
                        s = Random(0, 100);
                        waittime = 50;
                        if (SE == true)
                        {
                            if (CApp < 0) CApp = 0;
                            FaultPoints = (int)Math.Round(FaultPoints + (CApp * 1.5));
                            if (FaultPoints >= 25)
                            {
                                if (s > 50)
                                    SendMessage(ChatChannel.Friendly, "They figured out our strategy. Let\'s try something else.");
                                else
                                    SendMessage(ChatChannel.Friendly, "They are too strong from that side.");
                                FaultPoints = 25 - FaultPoints;
                                calattacks = calattacks / 3;
                                if (CapitalTask == 0)
                                {
                                    CapitalTask = 1;
                                    if (alliedcheck == true)
                                        SendMessage(ChatChannel.Friendly, "Everyone, we are now going to try to sneak attack the other players.");
                                }
                                else
                                {
                                    CapitalTask = 0;
                                    if (alliedcheck == true)
                                        SendMessage(ChatChannel.Friendly, "Everyone, we are now going to try to blitz the enemy capital.");
                                }
                            }
                            else if (FaultPoints >= 20)
                            {
                                if (s > 50)
                                    SendMessage(ChatChannel.All, "Come on now, just one more time and I will get him!");
                                else
                                    SendMessage(ChatChannel.All, "Let\'s do this one more time!");
                            }
                            else
                            {
                                if (s > 50)
                                    SendMessage(ChatChannel.All, "You will not be so lucky next time!");
                                else
                                    SendMessage(ChatChannel.All, "What in the world do you have there?");
                            }
                            if (currecaptar != Ecap.Name)
                            {
                                currecaptar = Ecap.Name;
                                if (oldecap.OwnedByMe == true)
                                {
                                    if (s > 50)
                                        SendMessage(ChatChannel.All, "Yes! I just conquered a capital.");
                                    else
                                        SendMessage(ChatChannel.All, "Another player bites the dust!");
                                }
                                oldecap = Ecap;
                            }
                        }
                        else
                        {
                            currecaptar = "";
                            FaultPoints = 0;
                            if (s > 50)
                                SendMessage(ChatChannel.All, "Yes! I just conquered a capital.");
                            else
                                SendMessage(ChatChannel.All, "Another player bites the dust!");
                        }
                        CApp = 32767.9;
                    }

                    PrintToDebug("FaultPoints=" + FaultPoints.ToString() + " CavalryAttack=" + CalAttack.ToString() + " AttackCount=" + attackcount.ToString() + " WarshipsReady=" + WarshipsReady.ToString(), EnD);
                    PrintToDebug("TotalAttackStrength=" + TotalAttackStrength.ToString() + " AvgAttackStrength=" + AvgAttackStrength.ToString() + " DefendWpn=" + defendwpn.ToString() + " CavalryWpn=" + cavalrywpn.ToString(), EnD);
                    PrintToDebug("VisibleThreats=" + VisibleShips.ToString() + " EWarships=" + EWarships.ToString() + " ClosestToCapital=" + CApp.ToString(), EnD);
                    PrintToDebug("MyCapX=" + mycapx.ToString() + " MyCapY=" + mycapy.ToString() + " CalAttacks=" + calattacks.ToString(), EnD);

                    #endregion

                    PrintToDebug("--------Bunker System And Pulsar Handler--------", EnD);

                    #region Bunker Scanner Coverage Systems and Pulsar Handler
                    //Build bunker system
                    List<bool> _PulsarCovered = new List<bool>();
                    List<bool> _PulsarSecured = new List<bool>();
                    for (int ii = 0; ii < Pulsars.Count; ii++)
                    {
                        _PulsarCovered.Add(false);
                        _PulsarSecured.Add(false);
                    }
                    StarShipInfo[] enemyshipindex = new StarShipInfo[Ships + 1];
                    int[] intenemyshipindex = new int[Ships + 1];
                    int filterind = 0;
                    int intDSDist = 99999;
                    int intRange = 10;
                    int ensnstar = 0;
                    string tmpstring = "";
                    StarShipInfo ShipNearStar = null;
                    if (EnemyShips > 0)
                    {
                        filterind = EnemyShips;
                        //find enemy starships near my starsystem
                        s = 0;
                        while (s < myalliedstars)
                        {
                            stari = myalliedstar[s];
                            ShipNearStar = ClosestStarShip(stari.X, stari.Y, 32767, FindShipFlags.Enemy, ShipKnownFlags.Either);
                            if (ShipNearStar != null)
                            {
                                if (Math.Abs(stari.X - ShipNearStar.X) > Math.Abs(stari.Y - ShipNearStar.Y))
                                    intDSDist = Math.Abs(stari.X - ShipNearStar.X);
                                else
                                    intDSDist = Math.Abs(stari.Y - ShipNearStar.Y);
                                if (intDSDist > intRange)
                                    ShipNearStar = null;
                            }
                            //if the ship is still valid, proceed with the scan, otherwise don`t waste time scanning empty spaces.
                            if (ShipNearStar != null)
                            {
                                ensnstar = 0;
                                //this code will give number of enemy starships are near every star i own
                                i = 0;
                                while (i < EnemyShips)
                                {
                                    shipi = enemyship[i];
                                    if (Math.Abs(stari.X - shipi.X) > Math.Abs(stari.Y - shipi.Y))
                                        intDSDist = Math.Abs(stari.X - shipi.X);
                                    else
                                        intDSDist = Math.Abs(stari.Y - shipi.Y);
                                    if (intDSDist > intRange)
                                        shipi = null;
                                    if (shipi != null)
                                    {
                                        ensnstar = ensnstar + 1;
                                        enemyshipindex[ensnstar - 1] = shipi;
                                    }
                                    i = i + 1;
                                }
                                _EnShipsNearStar[myalliedstar[s].Name] = ensnstar;
                                //finally, determine which starships are near a selected star
                                //now since I have found the number of starships are near a star, make a string with the list of starship codes.
                                //if there is a ship near this star, proceed with the list, otherwise don`t waste time.
                                tmpstring = "";
                                if (ensnstar > 0)
                                {
                                    i = 0;
                                    while (i < ensnstar)
                                    {
                                        tmpstring = tmpstring + enemyshipindex[i].Code + ",";
                                        i = i + 1;
                                    }
                                }
                                _EnShipList[myalliedstar[s].Name] = tmpstring;
                            }
                            else
                            {
                                //no ships near this star so set the variables to no starships status
                                _EnShipsNearStar[myalliedstar[s].Name] = 0;
                                _EnShipList[myalliedstar[s].Name] = "EOF";
                            }
                            s = s + 1;
                        }
                    }

                    //SendMessage(ChatChannel.All, "Debug4");


                    //Prototype scanner coverage code
                    int enborderstars = 0;
                    int myborderstars = 0;
                    int starscovered = 0;
                    int pulsarscovered = 0;
                    int pulsarssecured = 0;
                    //int starscovered = 0;
                    StarSystemInfo intBtar = null;
                    int intClosest = 99999;
                    bool placeonlist = false;
                    s = 0;
                    while (s < myalliedstars)
                    {
                        stari = myalliedstar[s];
                        if ((stari.Scanners >= 5) & (GetTerrain(stari.X, stari.Y) == TerrainType.Clear))
                        {
                            _StarCovered[stari.Name] = true;
                            i = 0;
                            while (i < myalliedstars)
                            {
                                mx = Math.Abs(myalliedstar[i].X - stari.X);
                                my = Math.Abs(myalliedstar[i].Y - stari.Y);
                                mx = mx * mx;
                                my = my * my;
                                floArcdist = Math.Sqrt(mx + my);
                                if (floArcdist <= stari.Scanners - 5)
                                    _StarCovered[myalliedstar[i].Name] = true;
                                i = i + 1;
                            }
                            for (int ii = 0; ii < Pulsars.Count; ii++)
                            {
                                mx = Math.Abs(Pulsars[ii].X - stari.X);
                                my = Math.Abs(Pulsars[ii].Y - stari.Y);
                                mx = mx * mx;
                                my = my * my;
                                floArcdist = Math.Sqrt(mx + my);
                                if (floArcdist <= stari.Scanners - 5)
                                    _PulsarCovered[ii] = true;
                            }
                        }
                        if (enemystars > 0)
                        {
                            //find closest enemy star from this star
                            i = 0;
                            intClosest = 99999;
                            intBtar = null;
                            intDSDist = 99999;
                            while (i < enemystars)
                            {
                                if (Math.Abs(stari.X - enemystar[i].X) > Math.Abs(stari.Y - enemystar[i].Y))
                                    intDSDist = Math.Abs(stari.X - enemystar[i].X);
                                else
                                    intDSDist = Math.Abs(stari.Y - enemystar[i].Y);
                                if (intDSDist < intClosest)
                                {
                                    intClosest = intDSDist;
                                    intBtar = enemystar[i];
                                }
                                i = i + 1;
                            }
                            if (intBtar != null)
                            {
                                //don`t place duplicate items on the border list.
                                placeonlist = true;
                                if (enborderstars > 0)
                                {
                                    i = 0;
                                    while (i < enborderstars)
                                    {
                                        if (enborderscan[i] == intBtar)
                                            placeonlist = false;
                                        i = i + 1;
                                    }
                                }
                                if (placeonlist == true)
                                {
                                    enborderstars = enborderstars + 1;
                                    enborderscan[enborderstars - 1] = intBtar;
                                }
                            }
                        }
                        s = s + 1;
                    }

                    //SendMessage(ChatChannel.All, "Debug5");

                    s = 0;
                    int mystarindex = 0;
                    while (s < enborderstars)
                    {
                        stari = enborderscan[s];
                        intClosest = 99999;
                        intBtar = null;
                        intDSDist = 99999;
                        i = 0;
                        while (i < myalliedstars)
                        {
                            if (Math.Abs(stari.X - myalliedstar[i].X) > Math.Abs(stari.Y - myalliedstar[i].Y))
                                intDSDist = Math.Abs(stari.X - myalliedstar[i].X);
                            else
                                intDSDist = Math.Abs(stari.Y - myalliedstar[i].Y);
                            if (intDSDist < intClosest)
                            {
                                intClosest = intDSDist;
                                mystarindex = i;
                                intBtar = myalliedstar[i];
                            }
                            if (_StarCovered[myalliedstar[i].Name] == true)
                                starscovered++;
                            i = i + 1;
                        }
                        if (intBtar != null)
                        {
                            if (_MyBorderScan[intBtar.Name] == false)
                            {
                                myborderstars = myborderstars + 1;
                                _MyBorderScan[intBtar.Name] = true;
                            }
                        }
                        s = s + 1;
                    }

                    PrintToDebug("MyBorderStars=" + myborderstars.ToString() + " EnemyBorderStars=" + enborderstars.ToString() + " MyStarsCovered=" + starscovered.ToString(), EnD);
                    #endregion

                    PrintToDebug("--------Pulsar Handler--------", EnD);

                    #region Pulsar Handler
                    //Detect if the pulsar is secured by my forces
                    int shipsfr = 0;
                    int shipsen = 0;
                    int shipfrdist = 99999;
                    int shipendist = 99999;
                    bool usepulsarrepair = false;
                    for (int ii = 0; ii < Pulsars.Count; ii++)
                    {
                        for (int ee = 0; ee < Alliedships; ee++)
                        {
                            shipi = alliedship[ee];
                            intDSDist = DistanceQuick(shipi.X, shipi.Y, Pulsars[ii].X, Pulsars[ii].Y);
                            if (intDSDist < shipfrdist)
                            {
                                shipfrdist = intDSDist;
                            }
                            if (intDSDist < (int)((TechMultiple / 5) + 1) * 10)
                            {
                                shipsfr++;
                            }
                            //double count if adjacent
                            if (IsAdjacentToCoords(shipi,Pulsars[ii].X, Pulsars[ii].Y) == true)
                            {
                                shipsfr++;
                            }
                        }
                        for (int ee = 0; ee < MyStarShips.Count; ee++)
                        {
                            shipi = MyStarShips[ee];
                            intDSDist = DistanceQuick(shipi.X, shipi.Y, Pulsars[ii].X, Pulsars[ii].Y);
                            if (intDSDist < shipfrdist)
                            {
                                shipfrdist = intDSDist;
                            }
                            if (intDSDist < (int)((TechMultiple / 5) + 1) * 10)
                            {
                                shipsfr++;
                            }
                            //double count if adjacent
                            if (IsAdjacentToCoords(shipi, Pulsars[ii].X, Pulsars[ii].Y) == true)
                            {
                                shipsfr++;
                            }
                        }
                        //5x count for nearby friendly stars
                        for (int ee = 0; ee < myalliedstars; ee++)
                        {
                            stari = myalliedstar[ee];
                            intDSDist = DistanceQuick(stari.X, stari.Y, Pulsars[ii].X, Pulsars[ii].Y);
                            if (intDSDist < shipfrdist)
                            {
                                shipfrdist = intDSDist;
                            }
                            if (intDSDist < (int)((TechMultiple / 5) + 1) * 10)
                            {
                                shipsfr = shipsfr + 5;
                            }
                        }
                        //count enemy starships 2x points
                        for (int ee = 0; ee < EnemyShips; ee++)
                        {
                            shipi = enemyship[ee];
                            intDSDist = DistanceQuick(shipi.X, shipi.Y, Pulsars[ii].X, Pulsars[ii].Y);
                            if (intDSDist < shipendist)
                            {
                                shipendist = intDSDist;
                            }
                            if (intDSDist < (int)(shipfrdist * 2) + 5)
                            {
                                shipsen = shipsen + 2;
                            }
                            //5x count if adjacent
                            if (IsAdjacentToCoords(shipi, Pulsars[ii].X, Pulsars[ii].Y) == true)
                            {
                                shipsen = shipsen + 3;
                            }
                        }
                        //10x count for nearby enemy stars
                        for (int ee = 0; ee < visiblestars; ee++)
                        {
                            stari = visstar[ee];
                            intDSDist = DistanceQuick(stari.X, stari.Y, Pulsars[ii].X, Pulsars[ii].Y);
                            if (intDSDist < shipfrdist)
                            {
                                shipendist = intDSDist;
                            }
                            if (intDSDist < (int)(shipfrdist * 2) + 5)
                            {
                                shipsen = shipsen + 10;
                            }
                        }
                        if (((_PulsarCovered[ii] = true) & (shipsen < shipsfr)) | (shipsen <= shipsfr / 2))
                        {
                            _PulsarSecured[ii] = true;
                            pulsarssecured++;
                        }

                        if (_PulsarCovered[ii] == true)
                            pulsarscovered++;
                    }
                    if (pulsarssecured > 0) usepulsarrepair = true;

                    PrintToDebug("PulsarsCovered=" + pulsarscovered.ToString() + " PulsarsSecured=" + pulsarssecured.ToString() + " UsePulsarRepair=" + usepulsarrepair.ToString(), EnD);

                    #endregion

                    PrintToDebug("--------Data Processing--------", EnD);

                    #region Data Processing
                    //detonate enemy madbombs if the reward is better then the risk
                    double ArcDistance = 0;
                    s = 0;
                    while (s < EnemyMBS)
                    {
                        ad = 0;
                        foreach (StarShipInfo ship in StarShips)
                        {
                            ArcDistance = Distance(ship.X, ship.Y, EnemyMB[s].X, EnemyMB[s].Y);
                            if (ArcDistance <= EnemyMB[s].Value)
                            {
                                if (ship.IdentifiedByMe == true)
                                {
                                    if ((ship.OwnedByMe == true) | (AlliedWithMe(ship.Owner) != AllianceLevel.None))
                                    {
                                        ad = ad - (ship.Engines * (ship.Value + 1));
                                    }
                                    else
                                    {
                                        ad = ad + (ship.Engines * (ship.Value + 1));
                                    }
                                }
                                else
                                {
                                    if (AlliedWithMe(ship.Owner) != AllianceLevel.None)
                                    {
                                        ad = ad - 25;
                                    }
                                    else
                                    {
                                        ad = ad + 25;
                                    }
                                }
                            }
                        }
                        //destroy visible enemy madbombs
                        if (ad >= 0)
                            DetonateMadBomb(EnemyMB[s]);
                        s = s + 1;
                    }

                    //Process Data.
                    StarShipInfo CEShip = null;
                    StarShipInfo MycapShip = null;
                    double EShipDist = 0;
                    int CapAlert = 0;
                    CEShip = ClosestStarShip(mycapx, mycapy, 15, FindShipFlags.Enemy, ShipKnownFlags.Either);
                    if (CEShip != null)
                    {
                        shipi = CEShip;
                        if (((mycapx - 10 < shipi.X) & (mycapy - 10 < shipi.Y) & (mycapx + 10 < shipi.X) & (mycapy + 10 < shipi.Y)) == false)
                        {
                            CEShip = null;
                        }
                    }

                    //SendMessage(ChatChannel.All, "Debug6.1");
                    PrintToDebug("Capital Alerts", EnD);

                    MycapShip = ClosestStarShip(mycapx, mycapy, 32767, FindShipFlags.Enemy, ShipKnownFlags.Either);
                    if (MycapShip != null)
                    {
                        EShipDist = Distance(mycapx, mycapy, MycapShip.X, MycapShip.Y);
                        if ((EShipDist < MinSTDist) & (STs > 0))
                            CapAlert = 1;
                        if ((EShipDist < 6 + (TechMultiple / 2)) | (CEShip != null))
                            CapAlert = 2;
                    }

                    alliedcheck = false;
                    for (int d = 0; d < 10; d++)
                    {
                        if (ECAPITAL[d] != null)
                        {
                            if (ECAPITALOWNER[d] != "")
                            {
                                if ((AlliedWithMe(ECAPITALOWNER[d]) != AllianceLevel.None) & (AlliedWith(ECAPITALOWNER[d]) != AllianceLevel.None))
                                {
                                    alliedcheck = true;
                                    if (ECAPITAL[d] != null)
                                    {
                                        MycapShip = ClosestStarShip(ECAPITAL[d].X, ECAPITAL[d].Y, 32767, FindShipFlags.Enemy, ShipKnownFlags.Either);
                                        if (MycapShip != null)
                                        {
                                            EShipADist = Distance(ECAPITAL[d].X, ECAPITAL[d].Y, MycapShip.X, MycapShip.Y);
                                            if ((_EshipsNearAlly[ECAPITALOWNER[d]] >= ECAPITAL[d].Shields) & (EShipADist < 6 + (TechMultiple / 2)))
                                            {
                                                if (messagestate == 0)
                                                {
                                                    SendMessage(ChatChannel.Friendly, ECAPITALOWNER[d] + ", your capital is under attack!");
                                                    messagestate = 1;
                                                }
                                            }
                                            else
                                            {
                                                messagestate = 0;
                                            }
                                        }
                                        else
                                        {
                                            messagestate = 0;
                                        }
                                    }
                                }
                            }

                        }
                    }

                    PrintToDebug("Player Alerts", EnD);

                    if (CapAlert != alertmessage)
                    {
                        if ((CapAlert == 1) & (alliedcheck == true))
                            SendMessage(ChatChannel.Friendly, "There are enemy starships inside the cluster!");
                        if ((CapAlert == 2) & (alliedcheck == true))
                            if (mycap.Shields < AlertPriority)
                                SendMessage(ChatChannel.Friendly, "My capital is under attack by " + MycapShip.Owner + "!");

                        alertmessage = CapAlert;
                    }
                    if (alertmessage != 3)
                    {
                        if ((CDAlert == true) & (alliedcheck == true))
                        {
                            tmpstring = "";
                            s = 0;
                            while (s < CDs)
                            {
                                if (CloakDet[s].CloakArrows.Count > 0)
                                    tmpstring = tmpstring + ", " + CloakDet[s].Code;
                                s++;
                            }

                            SendMessage(ChatChannel.Friendly, "I\'m detecting cloaked starships near cloakdetector(s)" + tmpstring + "!");

                            tmpstring = "Directions";
                            s = 0;
                            while (s < CDs)
                            {
                                if (CloakDet[s].CloakArrows.Count > 0)
                                {
                                    tmpstring = tmpstring + ":" + CloakDet[s].Code + ":";
                                    for (int d = 0; d < CloakDet[s].CloakArrows.Count; d++)
                                    {
                                        if (CloakDet[s].CloakArrows[d] == 0)  tmpstring = tmpstring + "N,";
                                        if (CloakDet[s].CloakArrows[d] == 1) tmpstring = tmpstring + "NE,";
                                        if (CloakDet[s].CloakArrows[d] == 2) tmpstring = tmpstring + "E,";
                                        if (CloakDet[s].CloakArrows[d] == 3) tmpstring = tmpstring + "SE,";
                                        if (CloakDet[s].CloakArrows[d] == 4) tmpstring = tmpstring + "S,";
                                        if (CloakDet[s].CloakArrows[d] == 5) tmpstring = tmpstring + "SW,";
                                        if (CloakDet[s].CloakArrows[d] == 6) tmpstring = tmpstring + "W,";
                                        if (CloakDet[s].CloakArrows[d] == 7) tmpstring = tmpstring + "NW,";
                                    }
                                }
                                s++;
                            }

                            SendMessage(ChatChannel.Friendly, tmpstring);

                            alertmessage = 3;
                        }
                    }

                    //SendMessage(ChatChannel.All, "Debug6.2");
                    PrintToDebug("Starship Management", EnD);

                    int StartilleryToScanshipRatio = 20;
                    int LevelUpStartilleryFactor = 20;
                    int LevelUpSacanshipFactor = Convert.ToInt32(LevelUpStartilleryFactor / StartilleryToScanshipRatio);
                    int SRange = 12;
                    if (SSs >= LevelUpSacanshipFactor * 1)
                        SRange = 15;
                    if (SSs >= LevelUpSacanshipFactor * 2)
                        SRange = 20;
                    if (SSs >= LevelUpSacanshipFactor * 4)
                        SRange = 30;
                    if (SSs >= LevelUpSacanshipFactor * 8)
                        SRange = 50;
                    if (SSs >= LevelUpSacanshipFactor * 16)
                        SRange = 100;
                    if (SSs >= LevelUpSacanshipFactor * 32)
                        SRange = 200;
                    int TRange = 8;
                    if (STs >= LevelUpStartilleryFactor * 1)
                        TRange = 12;
                    if (STs >= LevelUpStartilleryFactor * 2)
                        TRange = 18;
                    if (STs >= LevelUpStartilleryFactor * 4)
                        TRange = 30;
                    if (STs >= LevelUpStartilleryFactor * 8)
                        TRange = 50;
                    if (STs >= LevelUpStartilleryFactor * 16)
                        TRange = 100;
                    if (STs >= LevelUpStartilleryFactor * 32)
                        SRange = 200;
                    int tmprange = TRange;

                    //SendMessage(ChatChannel.All, "Debug6.3");

                    //Adjust engines as TM changes
                    int wareng0 = Convert.ToInt32((TechMultiple / 5) + 2);
                    int wareng1 = Convert.ToInt32((TechMultiple / 3) + 4);
                    int wareng2 = Convert.ToInt32(TechMultiple + 5);
                    int wareng3 = Convert.ToInt32(TechMultiple + 8);
                    int wareng4 = Convert.ToInt32((TechMultiple * 2) + 8);
                    int blitzeng = Convert.ToInt32((TechMultiple * 3) + 9);
                    if (wareng0 > 20) wareng0 = 20;
                    if (wareng1 > 20) wareng1 = 20;
                    if (wareng2 > 20) wareng2 = 20;
                    if (wareng3 > 20) wareng3 = 20;
                    if (wareng4 > 20) wareng4 = 20;
                    if (blitzeng > 20) blitzeng = 20;

                    //SendMessage(ChatChannel.All, "Debug6.4");

                    bool cloaker = false;
                    if (CloakedOpponent == true)
                    {
                        if ((TechMultiple >= 4.0) & (TechMultiple <= 5.0))
                            cloaker = (Random(0, 100) > 50);
                        if (TechMultiple >= 5.0)
                            cloaker = true;
                    }
                    else
                    {
                        if ((TechMultiple >= 7.0) & (TechMultiple <= 8.0))
                            cloaker = (Random(0, 100) > 50);
                        if (TechMultiple >= 8.0)
                            cloaker = true;
                    }

                    int CountSSs = SSs * StartilleryToScanshipRatio;
                    int CountRSs = RSs * 10;
                    int CountSTs = STs + MSs;

                    int STEng = 0;
                    if (STs < 4)
                        STEng = 12;
                    else
                        STEng = 20;

                    PrintToDebug("Calculate Field Unit", EnD);

                    //calculate which star will build the spyship while the other stars continue to build startillery.
                    StarSystemInfo goalstar = null;
                    double goalresources = 0;
                    int impulsestogo = 0;
                    int mitg = 99999;
                    double resinc = 0;
                    foreach (StarSystemInfo sys in StarSystems)
                    {
                        if ((sys.OwnedByMe == true) & (sys.IsCapital == false) & (sys.Value >= 12))
                        {
                            resinc = sys.Value;
                            if (CapitalTask == 1 && ParentScanship == null)
                            {
                                ad1 = SRange + 5;
                                if (ad1 < 20) ad1 = 20;
                                goalresources = ShipCostCalculator.GetCost(StarShipType.SpyShip, 20, ad1, true, null) - sys.Resources;
                                goalresources = goalresources / ((resinc / 40) * TechMultiple);
                                impulsestogo = (int)goalresources;
                                if (impulsestogo <= mitg)
                                {
                                    mitg = impulsestogo;
                                    goalstar = sys;
                                }
                            }
                            else if (ParentScanship == null)
                            {
                                if (STs > CountSSs)
                                {
                                    goalresources = ShipCostCalculator.GetCost(StarShipType.SpyShip, 20, SRange, true, null) - sys.Resources;
                                    goalresources = goalresources / ((resinc / 40) * TechMultiple);
                                    impulsestogo = (int)goalresources;
                                    if (impulsestogo <= mitg)
                                    {
                                        mitg = impulsestogo;
                                        goalstar = sys;
                                    }
                                }
                            }
                        }
                    }

                    PrintToDebug("Field Units", EnD);

                    //If i found a capital, do a risk calculation of the surrounding capital to determine if i can attack
                    int ecapships = 0;
                    Single ecapdefensecount = 0;
                    Single lionagression = 2.5F;
                    StarShipInfo[] sBeamShip = new StarShipInfo[MSs];
                    int tMSs = 0;
                    int fieldunits = 0;
                    if ((SE == true) & (EWarships > 0))
                        ecapdefensecount = ecapdefensecount + ((Ecap.Shields / AvgAttackStrength) * lionagression);
                    int CountedFieldUnits = STs + SSs + CDs + MSs + CSs + PSs;
                    StarShipInfo[] TRepair = new StarShipInfo[CountedFieldUnits + 1];
                    int[] TRepairLock = new int[CountedFieldUnits + 1];
                    int[] intTRepair = new int[CountedFieldUnits + 1];
                    TRepairLock[CountedFieldUnits] = -1;
                    TRepair[CountedFieldUnits] = null;
                    intTRepair[CountedFieldUnits] = -1;
                    int bunkerdrones = 0;
                    int meleedrones = 0;
                    int capitalobjects = 0;
                    s = 0;
                    foreach (StarShipInfo ship in StarShips)
                    {
                        if (ship.OwnedByMe == true)
                        {
                            if ((ship.ShipType == StarShipType.ScanShip) | (ship.ShipType == StarShipType.SpyShip) |
                                (ship.ShipType == StarShipType.StarTillery) | (ship.ShipType == StarShipType.BeamShip) |
                                (ship.ShipType == StarShipType.CloakDetector) | (ship.ShipType == StarShipType.CommandShip) |
                                (ship.ShipType == StarShipType.ParalyShip))
                            {
                                fieldunits = fieldunits + 1;
                                TRepair[fieldunits - 1] = ship;
                                TRepairLock[fieldunits - 1] = 0;
                                intTRepair[fieldunits - 1] = s;
                            }
                            if ((ship.ShipType == StarShipType.Drone) & (ship.ShipType == StarShipType.InkSpot))
                            {
                                if (ship.Engines > wareng1) bunkerdrones = bunkerdrones + 1;
                                if (ship.Engines < wareng1) meleedrones++;
                            }
                            if (((ship.Engines > wareng1) & ((ship.ShipType == StarShipType.Drone) |
                                (ship.ShipType == StarShipType.InkSpot))) | (ship.ShipType == StarShipType.EMine))
                                capitalobjects = capitalobjects + 1;
                            if (ship.ShipType == StarShipType.BeamShip)
                            {
                                tMSs++;
                                sBeamShip[tMSs - 1] = ship;
                                if (_BeamShipTarget.ContainsKey(ship.Code) == false)
                                    _BeamShipTarget.Add(ship.Code, null);
                                //Erase old target data
                                if (_BeamShipTarget[ship.Code] != null)
                                    _BeamShipTarget[ship.Code] = null;
                            }
                        }
                        else if (SE == true)
                        {
                            if ((ship.X >= Ecapx - 8) & (ship.Y >= Ecapy - 8) & (ship.X <= Ecapx + 8) & (ship.Y <= Ecapy + 8))
                            {
                                ecapships = ecapships + 1;
                                if (ship.IdentifiedByMe == false) ecapdefensecount = ecapdefensecount + 1;
                                if ((ship.ShipType == StarShipType.WarShip) & (ship.Value >= AvgAttackStrength - 3))
                                    ecapdefensecount = ecapdefensecount + (ship.Engines / 20);
                                if ((ship.ShipType == StarShipType.Elite) & (ship.Value >= AvgAttackStrength - 3))
                                    ecapdefensecount = ecapdefensecount + (ship.Engines / 20);
                                if (ship.ShipType == StarShipType.Drone) ecapdefensecount = ecapdefensecount + (ship.Engines / 15);
                                if (ship.ShipType == StarShipType.EMine) ecapdefensecount = ecapdefensecount + lionagression;
                                if (ship.ShipType == StarShipType.InkSpot) ecapdefensecount = ecapdefensecount + (ship.Engines / 40);
                                if (ship.ShipType == StarShipType.HijackShip) ecapdefensecount = ecapdefensecount + (ship.Engines / 15);
                                if (ship.ShipType == StarShipType.DoppleShip) ecapdefensecount = ecapdefensecount + (ship.Engines / 20);
                                if (ship.ShipType == StarShipType.StarTillery) ecapdefensecount = ecapdefensecount + (ship.Engines / 10);
                                if (ship.ShipType == StarShipType.BeamShip) ecapdefensecount = ecapdefensecount + (ship.Engines / 20);
                                if (ship.ShipType == StarShipType.ParalyShip) ecapdefensecount = ecapdefensecount + lionagression;
                            }
                        }
                        s = s + 1;
                    }

                    //SendMessage(ChatChannel.All, "Debug8");

                    double EcapShipsStr = Math.Round(ecapdefensecount);
                    if ((CapitalTask == 0) & (cloaker == true) & (mystars >= Stars / 3) & (TechMultiple >= 5) & (SE == false))
                    {
                        s = Random(0, 100);
                        if (s > 50)
                            SendMessage(ChatChannel.All, "You cannot hide any longer!");
                        else
                            SendMessage(ChatChannel.All, "I will find you!");

                        CapitalTask = 1;
                    }

                    double explimit = 8 + Math.Round(TechMultiple * 2);
                    if (explimit > Math.Round(Stars / 1.7)) explimit = Math.Round(Stars / 1.7);
                    bool Expand = (((mystars + alliedstars < Stars / 10) | (mystars + alliedstars < explimit / (alliedplayers + 1))) & (cloaker == false));

                    PrintToDebug("CapAlert=" + CapAlert.ToString() + " FieldUnits=" + fieldunits.ToString(), EnD);
                    PrintToDebug("SSRange=" + SRange.ToString() + " STRange=" + TRange.ToString() + " TechMultiple=" + TechMultiple.ToString(), EnD);
                    PrintToDebug("EcapShipsStr=" + EcapShipsStr.ToString() + " Cloaker=" + cloaker.ToString() + " ECapDefenseCount=" + ecapdefensecount.ToString(), EnD);
                    PrintToDebug("ExpandLimit=" + explimit.ToString() + " Expand=" + Expand.ToString() + " CapitalTask=" + CapitalTask.ToString(), EnD);
                    if (ParentScanship == null && goalstar != null)
                        PrintToDebug("GoalStar=" + goalstar.Name, EnD);

                    #endregion

                    PrintToDebug("--------SIAM Navigation--------", EnD);

                    //Contains Triggered DEBUGS!
                    #region 16 Direction SIAM Navigation System v4.07
                    //{SIAM (Super-Intelligent Analyzing Movement) 16-Bit Spyship Order Code SECTION *********************************************************************************************************}
                    //Now has a navigation debug screen!
                    #region Local Variables
                    double farthestdist = 0.001;
                    int TargetX = 0;
                    int TargetY = 0;
                    int direction = 0;
                    int direction2 = 0;
                    int HotZoneR = 0;
                    int hzx = 0;
                    int hzy = 0;
                    int sqdist = 0;
                    int intbuffer = 0;
                    bool obsalert = false;
                    int irange = 0;
                    bool df = false;
                    int a = 0;
                    int newdir = 0;
                    int obsrisk = 99999;
                    int[] shipdensity = new int[16];
                    StarShipInfo hzship = null;
                    StarSystemInfo GoToTarget = null;
#endregion

                    if (ParentScanship != null)
                    {
                        #region Planning and Target Code
                        shipi = ParentScanship;
                        SpyOrderX = shipi.X;
                        SpyOrderY = shipi.Y;
                        if (scanshipreturn == -1)
                            scanshipreturn = 0;
                        if (scanshipmode == -1)
                            scanshipmode = 0;
                        if (SE == false)
                        {
                            if (_shipTargetOrder.ContainsKey(shipi.Code) == false)
                                _shipTargetOrder.Add(shipi.Code, null);
                            if (_shipTargetOrder[shipi.Code] != null)
                            {
                                stari = _shipTargetOrder[shipi.Code];
                                if ((_LastStarOwner[stari.Name] > 0) & (stari.OwnedByMe == false))
                                    scanshipmode = 1;
                                if (_LastStarOwner[stari.Name] > -1)
                                    _shipTargetOrder[shipi.Code] = null;
                            }
                            if (_shipTargetOrder[shipi.Code] == null)
                            {
                                stari = null;
                                closestdist = 32767.9;
                                farthestdist = 0.001;
                                s = 0;
                                while (s < targets)
                                {
                                    floArcdist = Distance(TStar[s].X, TStar[s].Y, shipi.X, shipi.Y);
                                    if ((_LastStarOwner[TStar[s].Name] == -1) & (GetTerrain(TStar[s].X,TStar[s].Y) == TerrainType.Clear))
                                    {
                                        if (scanshipmode == 1)
                                        {
                                            if (floArcdist < closestdist)
                                            {
                                                stari = TStar[s];
                                                closestdist = floArcdist;
                                            }
                                        }
                                        else
                                        {
                                            if (floArcdist > farthestdist)
                                            {
                                                stari = TStar[s];
                                                farthestdist = floArcdist;
                                            }
                                        }
                                    }
                                    s = s + 1;
                                }
                                if (stari == null)
                                    stari = ClosestStarSystem(shipi.X, shipi.Y, 32767, FindSystemFlags.Unfriendly);
                                _shipTargetOrder[shipi.Code] = stari;
                            }
                            stari = _shipTargetOrder[shipi.Code];
                            GoToTarget = stari;
                            TargetX = stari.X;
                            TargetY = stari.Y;
                        }
                        else
                        {
                            if (CalAttack == true)
                            {
                                GoToTarget = Ecap;
                                if (Clusterx < Ecapx)
                                    TargetX = Ecapx + 10;
                                else
                                    TargetX = Ecapx - 10;
                                if (Clustery < Ecapy)
                                    TargetY = Ecapy + 10;
                                else
                                    TargetY = Ecapy - 10;
                            }
                            else
                            {
                                scanshipattack = false;
                                TargetX = mycapx;
                                TargetY = mycapy;
                                GoToTarget = mycap;
                            }
                        }
                        if (((shipi.X >= TargetX - 12) & (shipi.X <= TargetX + 12) & (shipi.Y >= TargetY - 12) & (shipi.Y <= TargetY + 12)) |
                            (((shipi.X >= Ecapx - 12) & (shipi.X <= Ecapx + 12) & (shipi.Y >= Ecapy - 12) & (shipi.Y <= Ecapy + 12)) &
                            ((EcapShipsStr < EWarships * lionagression) | closetocapital == true)))
                        {
                            if (TargetX == mycapx)
                            {
                                if (EWarships >= 2)
                                    scanshipreturn = 1;
                            }
                            else
                            {
                                if (CalAttack == true)
                                {
                                    if (alliedcheck == true)
                                        SendMessage(ChatChannel.Friendly, "ATTACK!");
                                    PrintToDebug("ATTACK!", EnD);
                                    //if (ECAPITAL[10] != null)
                                    //    TriggerDebugScreen(true, "TARGETING CAPITAL Star:" + Ecap.Name + " OB10:" + ECAPITAL[10].Name);
                                    //else
                                    //    TriggerDebugScreen(true, "TARGETING CAPITAL Star:" + Ecap.Name + " OB10:NONE!");
                                    scanshipattack = true;
                                    scanshipreturn = 0;
                                }
                            }
                        }
                        else if (closetocapital == false)
                        {
                            scanshipattack = false;
                        }
#endregion

                        //{begin SIAM navigation V2. 16-bit navigation. Created by beat2k.}

                        #region Data Collection
                        if (scanshipdirection == -1)
                            scanshipdirection = 0;
                        i = 0;
                        while (i < 16)
                        {
                            redirect[i] = 0;
                            shipdensity[i] = 0;
                            i = i + 1;
                        }
                        direction = 0;
                        direction2 = 0;
                        //prototype direction function
                        direction = FindDirection16(shipi.X, shipi.Y, TargetX, TargetY);
                        closestdist = 9999;
                        //if near the edge of map, prevent the spyship from moving out of the map
                        #region Border Patrol
                        if (shipi.Y <= 2)
                        {
                            redirect[13] = redirect[13] + 10000;
                            redirect[14] = redirect[14] + 10000;
                            redirect[15] = redirect[15] + 10000;
                            redirect[0] = redirect[0] + 10000;
                            redirect[1] = redirect[1] + 10000;
                            redirect[2] = redirect[2] + 10000;
                            redirect[3] = redirect[3] + 10000;
                        }
                        if (shipi.X <= 2)
                        {
                            redirect[9] = redirect[9] + 10000;
                            redirect[10] = redirect[10] + 10000;
                            redirect[11] = redirect[11] + 10000;
                            redirect[12] = redirect[12] + 10000;
                            redirect[13] = redirect[13] + 10000;
                            redirect[14] = redirect[14] + 10000;
                            redirect[15] = redirect[15] + 10000;
                        }
                        if (shipi.X >= mapx - 3)
                        {
                            redirect[4] = redirect[4] + 10000;
                            redirect[5] = redirect[5] + 10000;
                            redirect[6] = redirect[6] + 10000;
                            redirect[7] = redirect[1] + 10000;
                            redirect[1] = redirect[8] + 10000;
                            redirect[2] = redirect[2] + 10000;
                            redirect[3] = redirect[3] + 10000;
                        }
                        if (shipi.Y >= mapy - 3)
                        {
                            redirect[5] = redirect[5] + 10000;
                            redirect[6] = redirect[6] + 10000;
                            redirect[7] = redirect[7] + 10000;
                            redirect[8] = redirect[8] + 10000;
                            redirect[9] = redirect[9] + 10000;
                            redirect[10] = redirect[10] + 10000;
                            redirect[11] = redirect[11] + 10000;
                        }
                        #endregion
                        //find any enemy stars near my scanship.
                        #region Enemy Starsystems
                        s = 0;
                        while (s < visiblestars)
                        {
                            //HotZoneR is used to define the zone around a star where there is high risk. 0 = 1x1 ,1 = 3x3, 2 = 5x5, 3 = 7x7 etc..
                            //Find enemy ships next to a star
                            hzship = ClosestStarShip(visstar[s].X, visstar[s].Y, 2, FindShipFlags.Enemy, ShipKnownFlags.Either);
                            if (hzship != null)
                                HotZoneR = (EWarships / 8) + 2;
                            else
                                HotZoneR = (EWarships / 8) + 3;
                            //simple space distance calculator
                            sqdist = 9999;
                            if (visstar[s].X - shipi.X > visstar[s].Y - shipi.Y)
                                sqdist = visstar[s].X - shipi.X;
                            else
                                sqdist = visstar[s].Y - shipi.Y;
                            if (sqdist < 0)
                                sqdist = 0 - sqdist;
                            //find closest obstacle
                            if (sqdist < closestdist)
                                closestdist = sqdist;
                            intbuffer = (shipi.Engines / 2) + 1;
                            intbuffer = intbuffer + HotZoneR + 1;
                            if ((shipi.X - intbuffer <= visstar[s].X) & (shipi.Y - intbuffer <= visstar[s].Y) &
                                (shipi.X + intbuffer >= visstar[s].X) & (shipi.Y + intbuffer >= visstar[s].Y))
                            {
                                hzx = 0 - HotZoneR;
                                while (hzx <= HotZoneR)
                                {
                                    hzy = 0 - HotZoneR;
                                    while (hzy <= HotZoneR)
                                    {
                                        direction2 = FindDirection16(shipi.X, shipi.Y, (visstar[s].X + hzx), (visstar[s].Y + hzy));
                                        if ((direction2 > 0) & (direction2 < 17))
                                            redirect[direction2 - 1] = redirect[direction2 - 1] + 1;
                                        hzy = hzy + 1;
                                    }
                                    hzx = hzx + 1;
                                }
                            }
                            s = s + 1;
                        }
                        #endregion
                        //find any stars that are hidden by nebula
                        #region Nebula Starsystems
                        s = 0;
                        while (s < _NebulaStar.Count)
                        {
                            //HotZoneR is used to define the zone around a star where there is high risk. 0 = 1x1 ,1 = 3x3, 2 = 5x5, 3 = 7x7 etc..
                            //Find enemy ships next to a star
                            hzship = ClosestStarShip(_NebulaStar[s].X, _NebulaStar[s].Y, 2, FindShipFlags.Enemy, ShipKnownFlags.Either);
                            if (hzship != null)
                                HotZoneR = (EWarships / 8) + 2;
                            else
                                HotZoneR = (EWarships / 8) + 3;
                            //simple space distance calculator
                            sqdist = 9999;
                            if (_NebulaStar[s].X - shipi.X > _NebulaStar[s].Y - shipi.Y)
                                sqdist = _NebulaStar[s].X - shipi.X;
                            else
                                sqdist = _NebulaStar[s].Y - shipi.Y;
                            if (sqdist < 0)
                                sqdist = 0 - sqdist;
                            //find closest obstacle
                            if (sqdist < closestdist)
                                closestdist = sqdist;
                            intbuffer = (shipi.Engines / 2) + 1;
                            intbuffer = intbuffer + HotZoneR + 1;
                            if ((shipi.X - intbuffer <= _NebulaStar[s].X) & (shipi.Y - intbuffer <= _NebulaStar[s].Y) &
                                (shipi.X + intbuffer >= _NebulaStar[s].X) & (shipi.Y + intbuffer >= _NebulaStar[s].Y))
                            {
                                hzx = 0 - HotZoneR;
                                while (hzx <= HotZoneR)
                                {
                                    hzy = 0 - HotZoneR;
                                    while (hzy <= HotZoneR)
                                    {
                                        direction2 = FindDirection16(shipi.X, shipi.Y, (_NebulaStar[s].X + hzx), (_NebulaStar[s].Y + hzy));
                                        if ((direction2 > 0) & (direction2 < 17))
                                            redirect[direction2 - 1] = redirect[direction2 - 1] + 1;
                                        hzy = hzy + 1;
                                    }
                                    hzx = hzx + 1;
                                }
                            }
                            s = s + 1;
                        }
                        #endregion
                        //find enemy starships near my spyship
                        #region Enemy Starships
                        s = 0;
                        while (s < VisibleShips)
                        {
                            if (visship[s].ShipType != StarShipType.TechShip)
                            {
                                if (visship[s].ShipType == StarShipType.EMine)
                                    HotZoneR = (EWarships / 6) + 2;
                                else
                                    HotZoneR = (visship[s].Engines / 2) + 1;
                                intbuffer = (shipi.Engines / 2) + 2 + (EWarships / 4);
                                intbuffer = intbuffer + HotZoneR + 1;
                                if (HotZoneR > 7) HotZoneR = 7;
                                if ((shipi.X - intbuffer <= visship[s].X) & (shipi.Y - intbuffer <= visship[s].Y) &
                                    (shipi.X + intbuffer >= visship[s].X) & (shipi.Y + intbuffer >= visship[s].Y))
                                {
                                    hzx = 0 - HotZoneR;
                                    while (hzx <= HotZoneR)
                                    {
                                        hzy = 0 - HotZoneR;
                                        while (hzy <= HotZoneR)
                                        {
                                            direction2 = FindDirection16(shipi.X, shipi.Y, (visship[s].X + hzx), (visship[s].Y + hzy));
                                            if ((direction2 > 0) & (direction2 < 17))
                                                redirect[direction2 - 1] = redirect[direction2 - 1] + 1;
                                            hzy = hzy + 1;
                                        }
                                        hzx = hzx + 1;
                                    }
                                }
                            }
                            else
                            {
                                HotZoneR = (int)(EWarships / 8) + 1;
                                intbuffer = (shipi.Engines / 2) + (EWarships / 4) + 3;
                                if ((shipi.X - intbuffer <= visship[s].X) & (shipi.Y - intbuffer <= visship[s].Y) &
                                    (shipi.X + intbuffer >= visship[s].X) & (shipi.Y + intbuffer >= visship[s].Y))
                                {
                                    hzx = 0 - HotZoneR;
                                    while (hzx <= HotZoneR)
                                    {
                                        hzy = 0 - HotZoneR;
                                        while (hzy <= HotZoneR)
                                        {
                                            direction2 = FindDirection16(shipi.X, shipi.Y, (visship[s].X + hzx), (visship[s].Y + hzy));
                                            if ((direction2 > 0) & (direction2 < 17))
                                                shipdensity[direction2 - 1] = shipdensity[direction2 - 1] + 1;
                                            hzy = hzy + 1;
                                        }
                                        hzx = hzx + 1;
                                    }
                                }
                            }
                            s = s + 1;
                        }
                        #endregion
                        //find any wormholes or blackholes near my area.
                        #region Wormholes and Blackholes
                        s = 0;
                        foreach (WormholeInfo wh in Wormholes)
                        {
                            HotZoneR = 2;
                            intbuffer = (shipi.Engines / 2) + 1;
                            intbuffer = intbuffer + HotZoneR + 1;
                            if ((shipi.X - intbuffer <= wh.X) & (shipi.Y - intbuffer <= wh.Y) &
                                (shipi.X + intbuffer >= wh.X) & (shipi.Y + intbuffer >= wh.Y))
                            {
                                hzx = 0 - HotZoneR;
                                while (hzx <= HotZoneR)
                                {
                                    hzy = 0 - HotZoneR;
                                    while (hzy <= HotZoneR)
                                    {
                                        direction2 = FindDirection16(shipi.X, shipi.Y, (wh.X + hzx), (wh.Y + hzy));
                                        if ((direction2 > 0) & (direction2 < 17))
                                            redirect[direction2 - 1] = redirect[direction2 - 1] + 1;
                                        hzy = hzy + 1;
                                    }
                                    hzx = hzx + 1;
                                }
                            }
                        }
                        foreach (BlackHoleInfo bh in BlackHoles)
                        {
                            HotZoneR = 11;
                            intbuffer = (shipi.Engines / 2) + 1;
                            intbuffer = intbuffer + HotZoneR + 1;
                            if ((shipi.X - intbuffer <= bh.X) & (shipi.Y - intbuffer <= bh.Y) &
                                (shipi.X + intbuffer >= bh.X) & (shipi.Y + intbuffer >= bh.Y))
                            {
                                hzx = 0 - HotZoneR;
                                while (hzx <= HotZoneR)
                                {
                                    hzy = 0 - HotZoneR;
                                    while (hzy <= HotZoneR)
                                    {
                                        direction2 = FindDirection16(shipi.X, shipi.Y, (bh.X + hzx), (bh.Y + hzy));
                                        if ((direction2 > 0) & (direction2 < 17))
                                            redirect[direction2 - 1] = redirect[direction2 - 1] + 1;
                                        hzy = hzy + 1;
                                    }
                                    hzx = hzx + 1;
                                }
                            }
                        }
                        #endregion
                        // Dodge any potentially dangerous areas.
                        #region Enemy War Zones
                        foreach (Point pha in _EnemyIntensity.Keys)
                        {
                            if (_EnemyIntensity[pha] >= 25)
                            {
                                HotZoneR = (int)(_EnemyIntensity[pha] / 25);
                                if (HotZoneR > 7) HotZoneR = 7;
                                intbuffer = (shipi.Engines / 2) + 1;
                                intbuffer = intbuffer + HotZoneR + 1;
                                if ((shipi.X - intbuffer <= pha.X) & (shipi.Y - intbuffer <= pha.Y) &
                                    (shipi.X + intbuffer >= pha.X) & (shipi.Y + intbuffer >= pha.Y))
                                {
                                    hzx = 0 - HotZoneR;
                                    while (hzx <= HotZoneR)
                                    {
                                        hzy = 0 - HotZoneR;
                                        while (hzy <= HotZoneR)
                                        {
                                            direction2 = FindDirection16(shipi.X, shipi.Y, (pha.X + hzx), (pha.Y + hzy));
                                            if ((direction2 > 0) & (direction2 < 17))
                                                redirect[direction2 - 1] = redirect[direction2 - 1] + 1;
                                            hzy = hzy + 1;
                                        }
                                        hzx = hzx + 1;
                                    }
                                } 
                            }
                        }
                        #endregion
                        //(NEW!) Find large groups of friendly starships near my spyship
                        #region Friendly Crowded Areas
                        s = 0;
                        HotZoneR = (int)(Math.Sqrt(EWarships) / 5.0);
                        if (HotZoneR > 7) HotZoneR = 7;
                        while (s < MyStarShips.Count)
                        {
                            intbuffer = (shipi.Engines / 2) + 1;
                            if ((MyStarShips[s].ShipType != StarShipType.WarShip) & (MyStarShips[s].ShipType != StarShipType.DoppleShip) & (MyStarShips[s].ShipType != StarShipType.Elite))
                            {
                                if ((shipi.X - intbuffer <= MyStarShips[s].X) & (shipi.Y - intbuffer <= MyStarShips[s].Y) &
                                    (shipi.X + intbuffer >= MyStarShips[s].X) & (shipi.Y + intbuffer >= MyStarShips[s].Y))
                                {
                                    hzx = 0 - HotZoneR;
                                    while (hzx <= HotZoneR)
                                    {
                                        hzy = 0 - HotZoneR;
                                        while (hzy <= HotZoneR)
                                        {
                                            direction2 = FindDirection16(shipi.X, shipi.Y, MyStarShips[s].X, MyStarShips[s].Y);
                                            if ((direction2 > 0) & (direction2 < 17))
                                                shipdensity[direction2 - 1] = shipdensity[direction2 - 1] + 5;
                                            hzy = hzy + 1;
                                        }
                                        hzx = hzx + 1;
                                    }
                                }
                            }
                            s = s + 1;
                        }
                        s = 0;
                        while (s < Alliedships)
                        {
                            intbuffer = (shipi.Engines / 2) + 1;
                            if ((alliedship[s].ShipType != StarShipType.WarShip) & (alliedship[s].ShipType != StarShipType.DoppleShip) & (alliedship[s].ShipType != StarShipType.Elite))
                            {
                                if ((shipi.X - intbuffer <= alliedship[s].X) & (shipi.Y - intbuffer <= alliedship[s].Y) &
                                    (shipi.X + intbuffer >= alliedship[s].X) & (shipi.Y + intbuffer >= alliedship[s].Y))
                                {
                                    hzx = 0 - HotZoneR;
                                    while (hzx <= HotZoneR)
                                    {
                                        hzy = 0 - HotZoneR;
                                        while (hzy <= HotZoneR)
                                        {
                                            direction2 = FindDirection16(shipi.X, shipi.Y, alliedship[s].X, alliedship[s].Y);
                                            if ((direction2 > 0) & (direction2 < 17))
                                                shipdensity[direction2 - 1] = shipdensity[direction2 - 1] + 5;
                                            hzy = hzy + 1;
                                        }
                                        hzx = hzx + 1;
                                    }
                                }
                            }
                            s = s + 1;
                        }
                        #endregion
                        //analyze data. decreased size enormously!
                        obsalert = false;
                        tmpstring = "";
                        i = 0;
                        while (i < 16)
                        {
                            redirect[i] = redirect[i] - (int)(EWarships * lionagression);
                            //analyze density
                            redirect[i] = redirect[i] + (int)(shipdensity[i] / 20);
                            if (redirect[i] < 0) redirect[i] = 0;
                            tmpstring = tmpstring + redirect[i].ToString() + ",";
                            if (redirect[i] > 0)
                                obsalert = true;
                            i = i + 1;
                        }
                        PrintToDebug("ShipCode=" + shipi.Code + " Destination=" + GoToTarget.Name, EnD);
                        PrintToDebug("DirectionToTarget-1=" + direction.ToString() + " SpyshipDirection-1=" + scanshipdirection.ToString(), EnD);
                        PrintToDebug("cc " + tmpstring, EnD);
                        #endregion

                        #region Analysis and Course Correction
                        //analyze data if danger is detected..
                        if (obsalert == true)
                        {
                            df = false;
                            newdir = 0;
                            obsrisk = 99999;
                            i = 0;
                            while (i < 16)
                            {
                                if ((redirect[i] > 0) & (i + 1 == direction) & (df == false))
                                {
                                    //if there is a danger ahead and I have not found my new direction, find an alternate direction.
                                    irange = 0;
                                    while (irange < 9)
                                    {
                                        if (df == false)
                                        {
                                            s = 0 - irange;
                                            while (s <= irange)
                                            {
                                                a = scanshipdirection + s;
                                                if (a <= 0) a = a + 16;
                                                if (a >= 17) a = a - 16;
                                                if ((redirect[a - 1] < obsrisk) & (df == false))
                                                {
                                                    obsrisk = redirect[a - 1];
                                                    newdir = a;
                                                }
                                                if (redirect[a - 1] <= 0) df = true;
                                                s = s + 1;
                                            }
                                        }
                                        irange = irange + 1;
                                    }
                                }
                                else if ((redirect[i] == 0) & (i + 1 == direction) & (df == false))
                                {
                                    //clear straight ahead. no need to change direction.
                                    df = true;
                                    newdir = 0;
                                }
                                else if ((df == false) & (i + 1 >= direction - 1) & (i + 1 <= direction + 1))
                                {
                                    if (redirect[direction - 1] == 0)
                                    {
                                        //clear straight ahead. no need to change direction.
                                        df = true;
                                        newdir = direction;
                                    }
                                    else
                                    {
                                        //if it is not clear straight ahead but it is clear on an adjacent direction, change to the adjacent direction.
                                        for (int d = -1; d < 2; d++)
                                        {
                                            s = direction + d;
                                            if (s <= 0) s = s + 16;
                                            if (s >= 17) s = s - 16;
                                            if (redirect[s - 1] == 0)
                                            {
                                                df = true;
                                                newdir = s;
                                            }
                                        }
                                    }
                                }
                                i = i + 1;
                            }
                            if (newdir > 0) df = true;
                            //adjust course to drift towards target up to 45 degrees
                            if (newdir != direction)
                            {
                                //TriggerDebugScreen(true, "Dirdiff:" + GetDirectionDifference(newdir, direction, false).ToString());
                                PrintToDebug("DirectionDiff=" + GetDirectionDifference(newdir, direction, false).ToString(), EnD);
                                for (int ds = 1; ds <= 2; ds++)
                                {
                                    if (GetDirectionDifference(newdir, direction, false) > 0)
                                        s = newdir - 1;
                                    else
                                        s = newdir + 1;
                                    if (s <= 0) s = s + 16;
                                    if (s >= 17) s = s - 16;
                                    if (redirect[s - 1] == 0)
                                    {
                                        newdir = s;
                                    }
                                }
                                PrintToDebug("DirectionShiftedTo=" + newdir.ToString(), EnD);
                            }

                            irange = (shipi.Engines / 2) + 1;
                            if ((df == true) & (newdir > 0) & (scanshipattack == false))
                            {
                                //change to the new direction.
                                PrintToDebug("NewDirection=" + newdir.ToString(), EnD);
                                if (newdir == 1)
                                {
                                    SpyOrderX = shipi.X;
                                    SpyOrderY = shipi.Y - irange;
                                }
                                if (newdir == 2)
                                {
                                    SpyOrderX = shipi.X + (irange / 2);
                                    SpyOrderY = shipi.Y - irange;
                                }
                                if (newdir == 3)
                                {
                                    SpyOrderX = shipi.X + irange;
                                    SpyOrderY = shipi.Y - irange;
                                }
                                if (newdir == 4)
                                {
                                    SpyOrderX = shipi.X + irange;
                                    SpyOrderY = shipi.Y - (irange / 2);
                                }
                                if (newdir == 5)
                                {
                                    SpyOrderX = shipi.X + irange;
                                    SpyOrderY = shipi.Y;
                                }
                                if (newdir == 6)
                                {
                                    SpyOrderX = shipi.X + irange;
                                    SpyOrderY = shipi.Y + (irange / 2);
                                }
                                if (newdir == 7)
                                {
                                    SpyOrderX = shipi.X + irange;
                                    SpyOrderY = shipi.Y + irange;
                                }
                                if (newdir == 8)
                                {
                                    SpyOrderX = shipi.X + (irange / 2);
                                    SpyOrderY = shipi.Y + irange;
                                }
                                if (newdir == 9)
                                {
                                    SpyOrderX = shipi.X;
                                    SpyOrderY = shipi.Y + irange;
                                }
                                if (newdir == 10)
                                {
                                    SpyOrderX = shipi.X - (irange / 2);
                                    SpyOrderY = shipi.Y + irange;
                                }
                                if (newdir == 11)
                                {
                                    SpyOrderX = shipi.X - irange;
                                    SpyOrderY = shipi.Y + irange;
                                }
                                if (newdir == 12)
                                {
                                    SpyOrderX = shipi.X - irange;
                                    SpyOrderY = shipi.Y + (irange / 2);
                                }
                                if (newdir == 13)
                                {
                                    SpyOrderX = shipi.X - irange;
                                    SpyOrderY = shipi.Y;
                                }
                                if (newdir == 14)
                                {
                                    SpyOrderX = shipi.X - irange;
                                    SpyOrderY = shipi.Y - (irange / 2);
                                }
                                if (newdir == 15)
                                {
                                    SpyOrderX = shipi.X - irange;
                                    SpyOrderY = shipi.Y - irange;
                                }
                                if (newdir == 16)
                                {
                                    SpyOrderX = shipi.X - (irange / 2);
                                    SpyOrderY = shipi.Y - irange;
                                }
                                scanshipdirection = newdir;
                            }
                            else if (newdir == 0)
                            {
                                SpyOrderX = TargetX;
                                SpyOrderY = TargetY;
                                scanshipdirection = direction + 1;
                                PrintToDebug("NewDirection=" + scanshipdirection.ToString(), EnD);
                            }
                            else
                            {
                                SpyOrderX = shipi.X;
                                SpyOrderY = shipi.Y;
                                PrintToDebug("Spyship Stuck", EnD);
                            }
                        }
                        else
                        {
                            SpyOrderX = TargetX;
                            SpyOrderY = TargetY;
                            scanshipdirection = direction + 1;
                            PrintToDebug("NewDirection=" + scanshipdirection.ToString(), EnD);
                        }
                        Move(ParentScanship, SpyOrderX, SpyOrderY);

#endregion

                        //End SIAM Navigation
                    }
                    else
                    {
                        PrintToDebug("not available at this time", EnD);
                    }

                    //END SIAM 16-Bit Spyship Order Code SECTION ************************************************************************************************************************************************}
                    #endregion

                    PrintToDebug("--------Build Starships--------", EnD);
                    //if (CapAlert > 0) TriggerDebugScreen(true, "CAPITAL ALERT LEVEL " + CapAlert.ToString());
                    //variable buffer
                    #region Build Starships and StarSystem Management Section

                    //Build Starships from starsystems
                    #region Variables
                    StarShipInfo Eship1 = null;
                    StarShipInfo Eship2 = null;
                    StarSystemInfo Estar1 = null;
                    StarSystemInfo Estar2 = null;
                    StarSystemInfo Estar3 = null;
                    StarShipInfo LargeShip = null;
                    bool eBuild = false;
                    bool eDefend = false;
                    bool largewarning = false;
                    bool closecombatstart = false;
                    int nearvalue1 = 0;
                    int nearvalue2 = 0;
                    int expeng = 0;
                    int scapital = 0;
                    int shcapalert = 0;
                    int mindefendwpn = 0;
                    int buildspacesleft = 8;
                    double precal = 0;
                    double mimdist = 0;
                    double disttomycapship = 9999.9;
                    int xf = 0;
                    int TM = 0;
                    bool enemyhasstartillery = false;
                    bool parentspyshipbuilt = false;
                    s = 0;
                    TM = Convert.ToInt32(TechMultiple);
                    StarSystem tmpstarsystem = null;
                    precal = mystars * 3;
                    precal = (precal / targets);
                    if (precal == 0) precal = 0.000001;
                    precal = TechMultiple / precal;
                    precal = precal + 1;
                    precal = targets * precal;
                    PrintToDebug("StartilleryGroupUnitsNeededToSecureCluster=" + precal.ToString(), EnD);
                    #endregion
                    foreach (StarSystemInfo sys in StarSystems)
                    {
                        //tmpstarsys = tmpsvgame.FindStarSystem(sys.Name);
                        if (_ExpandOrder.ContainsKey(sys.Name) == false)
                            _ExpandOrder.Add(sys.Name, true);
                        if (sys.OwnedByMe == true)
                        {
                            #region StarSystem Intelligence
                            PrintToDebug("Start StarSystem " + sys.Name, EnD);
                            if (sys.AutoShields == true)
                                SetAutoShields(sys, false);
                            shipi = ClosestStarShip(sys.X, sys.Y, 32767, FindShipFlags.Enemy, ShipKnownFlags.Either);
                            if (shipi != null)
                                enemyhasstartillery = PlayerHasStartillery[shipi.OwnerInt];
                            if (enemyhasstartillery == false)
                                ad1 = 2 + (sys.Value / (20 + clusterdensity[sys.Name]));
                            else
                                ad1 = 1 + (sys.Value / (10 + clusterdensity[sys.Name]));
                            Eship1 = ClosestStarShip(sys.X, sys.Y, ad1 * 2, FindShipFlags.Enemy, ShipKnownFlags.Either);
                            if (Eship1 != null)
                            {
                                if (((sys.X - ad1 <= Eship1.X) & (sys.Y - ad1 <= Eship1.Y) & (sys.X + ad1 >= Eship1.X) & (sys.Y + ad1 >= Eship1.Y)) == false)
                                    Eship1 = null;
                            }
                            if (enemyhasstartillery == false)
                                ad1 = 4 + (sys.Value / (10 + clusterdensity[sys.Name]));
                            else
                                ad1 = 2 + (sys.Value / (5 + clusterdensity[sys.Name]));
                            Eship2 = ClosestStarShip(sys.X, sys.Y, ad1 * 2, FindShipFlags.Enemy, ShipKnownFlags.Either);
                            if (Eship2 != null)
                            {
                                if (((sys.X - ad1 <= Eship2.X) & (sys.Y - ad1 <= Eship2.Y) & (sys.X + ad1 >= Eship2.X) & (sys.Y + ad1 >= Eship2.Y)) == false)
                                    Eship2 = null;
                            }
                            nearvalue1 = 0;
                            nearvalue2 = 0;
                            stari = ClosestStarSystem(sys.X, sys.Y, 32767, FindSystemFlags.Unfriendly);
                            if (stari != null)
                            {
                                if (stari.OwnerInt > -1)
                                    enemyhasstartillery = PlayerHasStartillery[stari.OwnerInt];
                                else
                                    enemyhasstartillery = TEStartillery;
                            }
                            else
                            {
                                enemyhasstartillery = false;
                            }
                            if (enemyhasstartillery == false) ad1 = 12;
                            else if (cloaker == false) ad1 = 10;
                            else ad1 = 8;
                            Estar1 = ClosestStarSystem(sys.X, sys.Y, ad1 * 2, FindSystemFlags.Unfriendly);
                            if (Estar1 != null)
                            {
                                if (((sys.X - ad1 <= Estar1.X) & (sys.Y - ad1 <= Estar1.Y) & (sys.X + ad1 >= Estar1.X) & (sys.Y + ad1 >= Estar1.Y)) == false)
                                    Estar1 = null;
                                if (Estar1 != null)
                                    if ((Estar1.Visible == true) & (Estar1.Value < 6))
                                        Estar1 = null;
                            }
                            if (enemyhasstartillery == false) ad1 = 20;
                            else ad1 = 18;
                            Estar2 = ClosestStarSystem(sys.X, sys.Y, ad1 * 2, FindSystemFlags.Unfriendly);
                            if (Estar2 != null)
                            {
                                if (((sys.X - ad1 <= Estar2.X) & (sys.Y - ad1 <= Estar2.Y) & (sys.X + ad1 >= Estar2.X) & (sys.Y + ad1 >= Estar2.Y)) == false)
                                    Estar2 = null;
                            }
                            if (enemyhasstartillery == false) ad1 = 30;
                            else ad1 = 25;
                            Estar3 = ClosestStarSystem(sys.X, sys.Y, ad1 * 2, FindSystemFlags.Unfriendly);
                            if (Estar3 != null)
                            {
                                if (((sys.X - ad1 <= Estar3.X) & (sys.Y - ad1 <= Estar3.Y) & (sys.X + ad1 >= Estar3.X) & (sys.Y + ad1 >= Estar3.Y)) == false)
                                    Estar3 = null;
                            }
                            PrintToDebug("Expand Calculation " + sys.Name, EnD);
                            if (Estar1 != null) nearvalue1 = Estar1.Value + sys.Value;
                            if (Estar2 != null) nearvalue2 = Estar2.Value + sys.Value;
                            //Warship Engines adjust for the distance to nearest target and for TechMultiple.
                            if (sys.Resources <= 70 * (int)((TechMultiple / 4) + 0.75)) expeng = wareng2;
                            if (sys.Resources > 70 * (int)((TechMultiple / 4) + 0.75)) expeng = wareng3;
                            if (sys.Resources > 120 * (int)((TechMultiple / 4) + 0.75)) expeng = wareng4;
                            if (sys.Resources > 250 * (int)((TechMultiple / 4) + 0.75)) expeng = blitzeng;
                            if (stari != null)
                            {
                                mimdist = DistanceQuick(sys.X, sys.Y, stari.X, stari.Y);
                                if ((sys != mycap) | (knownstarshields < 15))
                                {
                                    if (mimdist <= 20 && expeng <= wareng2) expeng = wareng2;
                                }
                                else
                                {
                                    if (mimdist <= 20 && expeng <= wareng3) expeng = wareng2;
                                }
                                if (mimdist > 20 && mimdist <= 50 && expeng <= wareng3) expeng = wareng3;
                                if (mimdist > 50 && mimdist <= 150 && expeng <= wareng4) expeng = wareng4;
                                if (mimdist > 150 && expeng <= blitzeng) expeng = blitzeng;
                            }
                            PrintToDebug("Defense Calculation " + sys.Name, EnD);
                            //Large Starship Warning
                            largewarning = false;
                            for (int d = 0; d < LargeEnemies; d++)
                            {
                                LargeShip = _LargeEnemy[d];
                                if (LargeShip != null)
                                    if ((Math.Abs(LargeShip.X - sys.X) <= 13) & (Math.Abs(LargeShip.Y - sys.Y) <= 13))
                                        largewarning = true;
                            }
                            //Defense Vars.
                            eDefend = (Eship2 != null);
                            eBuild = (Eship1 != null);
                            if (eBuild == true)
                                _GetStarAttacks[sys.Name]++;

                            //Attack Warship Vars.
                            mindefendwpn = defendwpn / 2;
                            if (mindefendwpn <= minwarshipwpn)
                                mindefendwpn = minwarshipwpn;
                            PrintToDebug("Build Spaces " + sys.Name, EnD);
                            //Build Spaces
                            buildspacesleft = 8;
                            for (int d = 0; d < EnemyShips; d++)
                            {
                                shipi = enemyship[d];
                                if (shipi != null)
                                    if (shipi.X >= sys.X - 1 && shipi.Y >= sys.Y - 1 && shipi.X <= sys.X + 1 && shipi.Y <= sys.Y + 1)
                                        buildspacesleft--;
                            }
                            for (int d = 0; d < StarSystems.Count; d++)
                            {
                                stari = StarSystems[d];
                                if (stari != null)
                                    if (stari.X >= sys.X - 1 && stari.Y >= sys.Y - 1 && stari.X <= sys.X + 1 && stari.Y <= sys.Y + 1)
                                        if (stari != sys)
                                            buildspacesleft--;
                            }
                            #endregion
                            //MAIN SECTION
                            if (sys.IsCapital == true)
                            {
                                #region Capital Code
                                PrintToDebug("captial", EnD);
                                //My capital
                                scapital = ((sys.Value / 10) + (TM * 2) + 6);
                                shcapalert = scapital * 2;
                                scapital = scapital - sys.Shields;
                                shcapalert = shcapalert - sys.Shields;
                                if (scapital > 0) BuildShields(sys, scapital); //
                                if (defendwpn - 1 >= sys.Shields) BuildShields(sys, 5); //
                                //If my capital is under attack and I can't see the threat, build protection
                                if (MycapShip != null)
                                    disttomycapship = Distance(MycapShip.X, MycapShip.Y, sys.X, sys.Y);
                                if ((scapital > 0) & (((_GetStarAttacks[sys.Name] >= TM) & (closecombatmode == false)) | 
                                    ((_GetStarAttacks[sys.Name] >= TM + 2) & (closecombatmode == true))))
                                {
                                    SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                    SetAutoStarShip(sys, true);
                                    if (sys.Shields <= (TM * 2) + 4)
                                    {
                                        SetAutoShields(sys, true); //
                                    }
                                    if (MycapShip != null)
                                    {
                                        _TrustLevel[MycapShip.Owner] = _TrustLevel[MycapShip.Owner] / 3;
                                    }
                                }
                                //try a shot to take over the enemy capital if this game is not a multi-player game
                                else if ((SE == true) & (sys.Resources >= 95) & (sys.Resources <= 250) & (DistanceQuick(mycapx, mycapy, Ecapx, Ecapy) <= 18) & (IsMultiPlayerGame == false) & (numplayers == 2))
                                {
                                    if (closecombatmode == false)
                                    {
                                        _GetStarAttacks[sys.Name] = 2;
                                        ewpn = 5;
                                    }
                                    closecombatmode = true;
                                    closecombatstart = true;
                                    if (Ecapx > mycapx) xf = 0;
                                    else if (Ecapx == mycapx) xf = 3;
                                    else xf = 5;
                                    if (Ecapy < mycapy && xf != 3) xf = xf + 2;
                                    else if (Ecapy < mycapy && xf == 3) xf = xf + 1;
                                    else if (Ecapy == mycapy) xf = xf + 1;
                                    if ((knownstars <= 3) | (DistanceQuick(mycapx, mycapy, Ecapx, Ecapy) <= 4))
                                    {
                                        if (DistanceQuick(mycapx, mycapy, Ecapx, Ecapy) > 4)
                                        {
                                            for (int d = 0; d < 8; d++)
                                            {
                                                if (d == xf)
                                                {
                                                    BuildStarShip(sys, StarShipType.WarShip, wareng4, defendwpn, cloaker);
                                                }
                                                else
                                                    BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                            }
                                            BuildShields(sys, 1);
                                        }
                                        else
                                        {
                                            for (int d = 0; d < 8; d++)
                                            {
                                                if (d == xf)
                                                {
                                                    BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn - 1, cloaker);
                                                }
                                                else
                                                    BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        for (int d = 0; d < 8; d++)
                                        {
                                            if (d >= xf - 1 && d <= xf + 1)
                                            {
                                                if (d == xf)
                                                    BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn - 1, cloaker);
                                                else
                                                    BuildStarShip(sys, StarShipType.WarShip, wareng2, defendwpn - 2, cloaker);
                                            }
                                            else
                                                BuildStarShip(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                        }
                                        BuildShields(sys, 1);
                                    }
                                }
                                else if (CapAlert == 2)
                                {
                                    _TrustLevel[MycapShip.Owner] = _TrustLevel[MycapShip.Owner] / 1.5;
                                    // Someone is trying to take me over!
                                    if (AlertPriority >= 6)
                                    {
                                        if (sys.Resources > ((TM * 3) - 2) * 25)
                                        {
                                            BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                        }
                                        else if (sys.Resources > TM + 9)
                                        {
                                            BuildStarShip(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                            BuildStarShip(sys, StarShipType.WarShip, wareng0, defendwpn - 4, cloaker);
                                            SetAutoStarShipType(sys, StarShipType.Drone, wareng1, 0, cloaker);
                                            SetAutoStarShip(sys, true);
                                        }
                                        else
                                        {
                                            SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                            SetAutoStarShip(sys, true);
                                        }
                                        if (closecombatmode == false)
                                            BuildShields(sys, shcapalert);
                                    }
                                    else
                                    {
                                        if (sys.Resources > TM + 9)
                                        {
                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                        }
                                        else
                                        {
                                            SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                            SetAutoStarShip(sys, true);
                                        }
                                    }
                                }
                                else if (CapAlert == 1 && disttomycapship <= (TechMultiple * 8))
                                {
                                    _TrustLevel[MycapShip.Owner] = _TrustLevel[MycapShip.Owner] / 1.2;
                                    if (sys.Resources > (TM * 5) + 15)
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                    }
                                    else if (sys.Resources > TM + 9)
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng1, 0, cloaker);
                                    }
                                    else
                                    {
                                        SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                        SetAutoStarShip(sys, true);
                                    }
                                }
                                else if ((SE == true) & ((Expand == false) | (sys.Resources >= 1100)) & (TM >= 4))
                                {
                                    //If I spotted a capital, help with the building of attack warships.
                                    if (CalAttack == true)
                                    {
                                        if (DefendWarships >= mystars / 4)
                                        {
                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                        }
                                        else
                                        {
                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng4, Random(defendwpn, defendwpn + 2), cloaker);
                                        }
                                    }
                                    else if (capitalobjects < (TM * 2) + 6)
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                    }
                                    else
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, blitzeng, defendwpn + 4, cloaker);
                                    }
                                }
                                else if ((Expand == true) & (sys.Resources >= 7500))
                                {
                                    ad2 = 6 - (Stars / 50);
                                    if (Stars < 20) ad2 = ad2 + 1;
                                    if (ad2 < 1) ad2 = 1;
                                    if (STs == 0)
                                        for (int d = 0; d < ad2; d++) BuildStarShip(sys, StarShipType.StarTillery, 20, 20, true);
                                    if (SSs == 0)
                                        BuildStarShip(sys, StarShipType.SpyShip, 20, 25, true);
                                    if (STs > 0)
                                    {
                                        for (int d = 0; d < 1; d++) BuildStarShip(sys, StarShipType.Drone, 20, 0, true);
                                        for (int d = 0; d < 6; d++) BuildStarShip(sys, StarShipType.WarShip, 20, Random(defendwpn + 10, defendwpn + 25), true);
                                        for (int d = 0; d < 1; d++) BuildStarShip(sys, StarShipType.InkSpot, 20, 0, true);
                                    }
                                    else
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, expeng, Random(defendwpn + 10, defendwpn + 25), true);

                                        SetAutoStarShipType(sys, StarShipType.WarShip, expeng, Random(defendwpn + 10, defendwpn + 25), cloaker);
                                        SetAutoStarShip(sys, true);
                                    }
                                }
                                else if ((Expand == true) & (sys.Resources >= 2500))
                                {
                                    ad2 = 4 - (Stars / 50);
                                    if (Stars < 20) ad2 = ad2 + 1;
                                    if (ad2 < 1) ad2 = 1;
                                    if (STs == 0)
                                        for (int d = 0; d < ad2; d++) BuildStarShip(sys, StarShipType.StarTillery, 20, 15, true);
                                    if (SSs == 0)
                                        BuildStarShip(sys, StarShipType.SpyShip, 20, 20, true);
                                    if (STs > 0)
                                    {
                                        for (int d = 0; d < 1; d++) BuildStarShip(sys, StarShipType.Drone, wareng4, 0, true);
                                        for (int d = 0; d < 5; d++) BuildStarShip(sys, StarShipType.WarShip, expeng, Random(defendwpn - 1, defendwpn + 10), cloaker);
                                        for (int d = 0; d < 2; d++) BuildStarShip(sys, StarShipType.InkSpot, wareng4, 0, true);
                                    }
                                    else
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, expeng, Random(defendwpn - 1, defendwpn + 10), cloaker);

                                        SetAutoStarShipType(sys, StarShipType.WarShip, expeng, Random(defendwpn - 1, defendwpn + 10), cloaker);
                                        SetAutoStarShip(sys, true);
                                    }
                                }
                                else if ((Expand == true) & (sys.Resources >= 700))
                                {
                                    ad2 = 2 - (Stars / 50);
                                    if (Stars < 20) ad2 = ad2 + 1;
                                    if (ad2 < 1) ad2 = 1;
                                    //for debugging purposes only!!
                                    if (testbuild == false && builddebug == true)
                                    {
                                        for (int d = 0; d < 1; d++) BuildStarShip(sys, debugstarship, 20, 0, true);
                                        testbuild = true;
                                    }
                                    //for debugging purposes only!!
                                    if (STs == 0)
                                        for (int d = 0; d < ad2; d++) BuildStarShip(sys, StarShipType.StarTillery, 20, 16, cloaker);
                                    if (SSs == 0)
                                        BuildStarShip(sys, StarShipType.SpyShip, 20, 16, false);
                                    if (STs > 0)
                                    {
                                        for (int d = 0; d < 1; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                        for (int d = 0; d < 6; d++) BuildStarShip(sys, StarShipType.WarShip, expeng, Random(mindefendwpn, defendwpn - 1), cloaker);
                                        for (int d = 0; d < 1; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                    }
                                    else
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, expeng, Random(minwarshipwpn, defendwpn - 1), cloaker);

                                        SetAutoStarShipType(sys, StarShipType.WarShip, expeng, Random(minwarshipwpn, defendwpn - 1), cloaker);
                                        SetAutoStarShip(sys, true);
                                    }
                                }
                                else if (((closecombatmode == false) | ((closecombatmode == true) & (mystars <= 3) & (sys.Resources < (TM * 6) + 6))) & 
                                        ((Expand == true) & ((mystars < Stars / 3) | (Estar1 != null))))
                                {
                                    //build expand warships from capital until I have reached a good enough size}
                                    if ((sys.Resources >= 112) & ((SSs >= 1) | (STs >= 1)))
                                    {
                                        for (int d = 0; d < 1; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                        for (int d = 0; d < 5; d++) BuildStarShip(sys, StarShipType.WarShip, expeng, Random(mindefendwpn, defendwpn - 1), cloaker);
                                        for (int d = 0; d < 2; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                    }
                                    else if (sys.Resources < 112 && sys.Resources > 95)
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, expeng, Random(minwarshipwpn, defendwpn - 2), cloaker);
                                    }
                                    else
                                    {
                                        SetAutoStarShipType(sys, StarShipType.WarShip, expeng, Random(minwarshipwpn, defendwpn - 2), cloaker);
                                        SetAutoStarShip(sys, true);
                                    }
                                }
                                else if ((capitalobjects < (int)(TechMultiple * 3)) | ((closecombatmode == true) & (sys.Resources >= (TM * 6) + 4)))
                                {
                                    //New Section: Build defense drones from capital
                                    SetAutoStarShipType(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                    SetAutoStarShip(sys, true);
                                }
                                else if ((sys.Resources >= 1950) & (TM < 2))
                                {
                                    SetAutoStarShipType(sys, StarShipType.WarShip, 20, Random(defendwpn - 1, defendwpn + 10), true);
                                    SetAutoStarShip(sys, true);
                                }
                                else if ((sys.Resources >= 950) & (TM < 2))
                                {
                                    for (int d = 0; d < 1; d++) BuildStarShip(sys, StarShipType.Drone, wareng4, 0, true);
                                    for (int d = 0; d < 6; d++) BuildStarShip(sys, StarShipType.WarShip, 20, Random(defendwpn - 1, defendwpn + 10), false);
                                    for (int d = 0; d < 1; d++) BuildStarShip(sys, StarShipType.Drone, wareng4, 0, true);
                                }
                                else if (TM <= 8)
                                {
                                    //Build techships as soon as possible}
                                    SetAutoStarShipType(sys, StarShipType.TechShip, 3, 0, false);
                                    SetAutoStarShip(sys, true);
                                }
                                else if ((STs < 10) | (SSs < 1))
                                {
                                    //Use capital as big star for building startillery or spyships}
                                    if (STs <= CountSSs)
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                    }
                                    if (CountSSs <= STs) BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                    //SendMessage(ChatChannel.All, "Build5");
                                }
                                else if (capitalobjects < (TM * 6) + 6)
                                {
                                    //Build up capital bunker}
                                    for (int d = 0; d < 8; d++)
                                    {
                                        if (Random(0, 100) < 70)
                                            BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                        else
                                            BuildStarShip(sys, StarShipType.InkSpot, wareng3, 0, cloaker);
                                    }
                                }
                                else if (_UsefulStarships.ContainsValue(sys.BonusShipType) == true)
                                {
                                    //BONUS STARSHIP BUILDING!                                    
                                    if (sys.BonusShipType == StarShipType.EMine)
                                    {
                                        if (capitalobjects < (TM * 2) + 6)
                                            BuildStarShip(sys, StarShipType.EMine, 1, 0, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    if (sys.BonusShipType == StarShipType.StarTillery)
                                    {
                                        if (STs <= CountSSs)
                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if (sys.BonusShipType == StarShipType.SpyShip)
                                    {
                                        if (CountSSs <= STs)
                                            BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if (sys.BonusShipType == StarShipType.RepairShip)
                                    {
                                        if (RSs < (STs + SSs) / 10)
                                            BuildStarShip(sys, StarShipType.RepairShip, 20, 0, true);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if (sys.BonusShipType == StarShipType.ShieldGenerator)
                                    {
                                        if (SGs < NumGoodStars)
                                            BuildStarShip(sys, StarShipType.ShieldGenerator, 20, 0, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if (sys.BonusShipType == StarShipType.CommandShip)
                                    {
                                        if (CSs < (STs / 2))
                                            BuildStarShip(sys, StarShipType.CommandShip, 20, SRange, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if (sys.BonusShipType == StarShipType.MadBomb)
                                    {
                                        if ((SE == true) & (CalAttack == false))
                                            BuildStarShip(sys, StarShipType.MadBomb, 20, TRange, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if (sys.BonusShipType == StarShipType.CloakDetector)
                                    {
                                        if (CDs < (STs + SSs) / 10)
                                            BuildStarShip(sys, StarShipType.CloakDetector, 20, SRange, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if (sys.BonusShipType == StarShipType.BeamShip)
                                    {
                                        if (MSs < (STs + SSs) / 5)
                                            BuildStarShip(sys, StarShipType.BeamShip, 20, TRange, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if ((sys.BonusShipType == StarShipType.HijackShip) |
                                             (sys.BonusShipType == StarShipType.InkSpot) |
                                             (sys.BonusShipType == StarShipType.Drone))
                                    {
                                        if (capitalobjects < (TM * 2) + 6)
                                            BuildStarShip(sys, sys.BonusShipType, wareng3, 0, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if (sys.BonusShipType == StarShipType.MineSweeper)
                                    {
                                        if ((SE == true) & (CalAttack == false))
                                        {
                                            if (_EnemyHasMines[EcapOwner] == true)
                                                BuildStarShip(sys, StarShipType.MineSweeper, 20, TRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else
                                        {
                                            goto techshipbuild;
                                        }
                                    }
                                    else if (sys.BonusShipType == StarShipType.BattleStation)
                                    {
                                        if (BSs < (STs + SSs) / 20)
                                            BuildStarShip(sys, StarShipType.BattleStation, 6, SRange, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if ((sys.BonusShipType == StarShipType.WarShip) |
                                             (sys.BonusShipType == StarShipType.Elite) |
                                             (sys.BonusShipType == StarShipType.DoppleShip))
                                    {
                                        if ((SE == true) & (CalAttack == false))
                                            BuildStarShip(sys, sys.BonusShipType, blitzeng, defendwpn + 4, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if (sys.BonusShipType == StarShipType.ParalyShip)
                                    {
                                        if (PSs < STs)
                                            BuildStarShip(sys, StarShipType.ParalyShip, 20, TRange, cloaker);
                                        else
                                            goto techshipbuild;
                                    }
                                    else if (sys.BonusShipType == StarShipType.RemoteViewer)
                                    {
                                        if (RVs < (SSs / 3))
                                            BuildStarShip(sys, StarShipType.RemoteViewer, 20, SRange, cloaker);
                                        else
                                            goto techshipbuild;
                                    }

                                    goto skiptechshipbuild;
                                techshipbuild:
                                    {
                                        //I have nothing more to do so build up shields or startillery}
                                        scapital = ((sys.Value / 10) + (TM * 3) + 6);
                                        scapital = scapital - sys.Shields;
                                        if (scapital > 0) BuildShields(sys, scapital + Random(0, 5));
                                        if (CapitalTask == 0)
                                        {
                                            if (STs <= CountSSs)
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                            }
                                            if (CountSSs <= STs) BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                        }
                                        else if (ParentScanship == null)
                                        {
                                            BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, true);
                                        }
                                        else
                                        {
                                            if (STs <= CountSSs)
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                            }
                                            if (CountSSs <= STs) BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                        }
                                    }
                                skiptechshipbuild:
                                    {
                                        //
                                    }
                                }
                                else
                                {
                                    //I have nothing more to do so build up shields or startillery}
                                    scapital = ((sys.Value / 10) + (TM * 3) + 6);
                                    scapital = scapital - sys.Shields;
                                    if (scapital > 0) BuildShields(sys, scapital + Random(0, 5));
                                    if (CapitalTask == 0)
                                    {
                                        if (STs <= CountSSs)
                                        {
                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                        }
                                        if (CountSSs <= STs) BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                    }
                                    else if (ParentScanship == null)
                                    {
                                        BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, true);
                                    }
                                    else
                                    {
                                        if (STs <= CountSSs)
                                        {
                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                        }
                                        if (CountSSs <= STs) BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                    }
                                }
#endregion
                            }
                            else
                            {
                                //Other stars
                                #region Init Defense Code
                                ad3 = _GetStarAttacks[sys.Name];
                                ad1 = (ad3 * (sys.Value / 4)) - (TM * 2);
                                if (sys.Shields < ad1)
                                {
                                    BuildShields(sys, ad1 - sys.Shields);
                                    if (_RecoveryTime[sys.Name] > 0)
                                    {
                                        SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                        SetAutoStarShip(sys, true);
                                    }
                                }
                                if ((_MyBorderScan[sys.Name] == true) & (eDefend == true))
                                {
                                    BuildShields(sys, TM * 4);
                                    if (cloaker == true) 
                                    {
                                        SetAutoStarShipType(sys, StarShipType.InkSpot, wareng0, 0, cloaker);
                                    }
                                    else
                                    {
                                        SetAutoStarShipType(sys, StarShipType.Drone, Random(wareng0, wareng1), 0, cloaker);
                                    }
                                    SetAutoStarShip(sys, true);
                                }
                                #endregion
                                if (sys.Value >= 12)
                                {
                                    #region LargeStar
                                    PrintToDebug("largestar", EnD);
                                    if (((eDefend == true) | (Estar1 != null)) & (Expand == false) & (_ExpandOrder[sys.Name] == false))
                                    //if ((eDefend == true) & (_ExpandOrder[sys.Name] == false))
                                    {
                                        if (sys.Resources >= 28 + (TM * 2))
                                        {
                                            ad3 = 0;
                                            if (cloaker == false)
                                            {
                                                ad1 = 12;
                                                ad2 = 0;
                                                for (int d = 5; d < 8; d++)
                                                {
                                                    if (ShipCostCalculator.GetCost(StarShipType.StarTillery, ad1, d, cloaker, tmpstarsystem) <= sys.Resources)
                                                    {
                                                        ad2 = d;
                                                        ad3 = ad1;
                                                    }
                                                }
                                            }
                                            ad1 = 20;
                                            for (int d = 5; d < TRange; d++)
                                            {
                                                if (ShipCostCalculator.GetCost(StarShipType.StarTillery, ad1, d, cloaker, tmpstarsystem) <= sys.Resources)
                                                {
                                                    ad2 = d;
                                                    ad3 = ad1;
                                                }
                                            }
                                            if (ad3 > 0)
                                            {
                                                if (ad2 == TRange)
                                                {
                                                    for (int d = 0; d < 8; d++)
                                                        BuildStarShip(sys, StarShipType.StarTillery, ad1, ad3, cloaker);
                                                }
                                                else
                                                {
                                                    BuildStarShip(sys, StarShipType.StarTillery, ad1, ad3, cloaker);
                                                }
                                            }
                                        }
                                    }
                                    if (((_StarCovered[sys.Name] == false) | (sys.Scanners < tmprange)) & (_ExpandOrder[sys.Name] == false) &
                                        (Expand == false) & (STs >= 2) & (_MyBorderScan[sys.Name] == true) & (Estar1 != null))
                                        BuildScanners(sys, 5);
                                    if (cloaker == true)
                                    {
                                        if ((_MyBorderScan[sys.Name] == true) & (sys.Resources < (TM * 50)))
                                            for (int d = 0; d < 8; d++)
                                                BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, cloaker);
                                    }
                                    if ((eDefend == true) & (_ExpandOrder[sys.Name] == false))
                                    {
                                        BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, cloaker); //
                                        BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                        for (int d = 0; d < 8; d++)
                                        {
                                            enemyhasstartillery = PlayerHasStartillery[Eship2.OwnerInt];
                                            if (cloaker == true) BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, cloaker);
                                            if (sys.Resources > (TM * 5) + 15)
                                            {
                                                if (enemyhasstartillery == false)
                                                    BuildStarShip(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                                else
                                                    BuildStarShip(sys, StarShipType.Drone, Random(wareng1, wareng2), 0, cloaker);
                                            }
                                            else
                                            {
                                                if (enemyhasstartillery == false)
                                                    BuildStarShip(sys, StarShipType.Drone, Random(wareng1, wareng2), 0, cloaker);
                                                else
                                                    BuildStarShip(sys, StarShipType.Drone, Random(wareng0, wareng1), 0, cloaker);
                                            }
                                        }
                                    }
                                    PrintToDebug("afterdefend", EnD);
                                    if ((Estar1 != null) | ((Expand == true) & (((TM < 4) & (CloakedOpponent == true)) | (TM < 6) & (CloakedOpponent == false)) & (Estar2 != null)) | (_ExpandOrder[sys.Name] == true) | (_MyBorderScan[sys.Name] == true))
                                    {
                                        if (((Expand == true) & (((TM < 4) & (CloakedOpponent == true)) | (TM < 6) & (CloakedOpponent == false))) | (_ExpandOrder[sys.Name] == true))
                                        {
                                            ad1 = Random(mindefendwpn, defendwpn - 1);
                                            SetAutoStarShipType(sys, StarShipType.WarShip, expeng, ad1, cloaker);
                                            SetAutoStarShip(sys, true);
                                        }
                                        else if (Estar1 != null)
                                        {
                                            ad1 = Random(mindefendwpn, defendwpn - 1);
                                            if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.WarShip, expeng, ad1, cloaker, tmpstarsystem))
                                            {
                                                if (_ExpandOrder[sys.Name] == false) BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);

                                                SetAutoStarShipType(sys, StarShipType.WarShip, expeng, ad1, cloaker);
                                                SetAutoStarShip(sys, true);
                                            }
                                        }
                                        else
                                        {
                                            ad1 = Random(mindefendwpn, defendwpn - 1);
                                            SetAutoStarShipType(sys, StarShipType.WarShip, expeng, ad1, cloaker);
                                            SetAutoStarShip(sys, true);
                                        }
                                        PrintToDebug("d1", EnD);
                                    }
                                    else if (Estar1 == null)
                                    {
                                        if ((CapAlert == 2) & (Distance(sys.X, sys.Y, mycapx, mycapy) <= 15))
                                        {
                                            if (sys.Resources <= (ShipCostCalculator.GetCost(StarShipType.StarTillery, STEng, TRange, cloaker, tmpstarsystem) / 1.4))
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                            }
                                        }
                                        else if (CapAlert == 2)
                                        {
                                            if (sys.Resources <= (ShipCostCalculator.GetCost(StarShipType.StarTillery, STEng, TRange, cloaker, tmpstarsystem) / 1.4))
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                            }
                                        }
                                        calculation = mystars * 3;
                                        calculation = (calculation / targets);
                                        if (calculation == 0) calculation = 0.000001;
                                        if (STs + SSs >= targets * ((TechMultiple / calculation) + 1))
                                        {
                                            if (SE == true)
                                            {
                                                if (CalAttack == true)
                                                {
                                                    if (DefendWarships >= mystars / 4)
                                                    {
                                                        if (capitalobjects >= (TM * 6) + 6)
                                                        {
                                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.TechShip, 3, 0, false);
                                                        }
                                                        else
                                                        {
                                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (STs + SSs >= (TM * 6) + 2)
                                                        {
                                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.TechShip, 3, 0, false);
                                                        }
                                                        else
                                                        {
                                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng3, Random(defendwpn, defendwpn + 1), cloaker);
                                                        }
                                                    }
                                                }
                                                else if ((CapitalTask == 1) & (ParentScanship == null) & (sys == goalstar))
                                                {
                                                    if (parentspyshipbuilt == false)
                                                    {
                                                        ad1 = SRange + 5;
                                                        if (ad1 < 20) ad1 = 20;
                                                        if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.SpyShip, 20, ad1, true, tmpstarsystem))
                                                        {
                                                            BuildStarShip(sys, StarShipType.SpyShip, 20, ad1, true);
                                                            parentspyshipbuilt = true;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.StarTillery, STEng, TRange, cloaker, tmpstarsystem))
                                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                                    }
                                                }
                                                else if (capitalobjects < (TM * 2) + 6)
                                                {
                                                    for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                                }
                                                else if (CalAttack == false)
                                                {
                                                    for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, blitzeng, defendwpn + 4, cloaker);
                                                }
                                            }
                                            else if ((CapitalTask == 1) & (ParentScanship == null) & (sys == goalstar))
                                            {
                                                if (parentspyshipbuilt == false)
                                                {
                                                    ad1 = SRange + 5;
                                                    if (ad1 < 20) ad1 = 20;
                                                    if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.SpyShip, 20, ad1, true, tmpstarsystem))
                                                    {
                                                        BuildStarShip(sys, StarShipType.SpyShip, 20, ad1, true);
                                                        parentspyshipbuilt = true;
                                                    }
                                                }
                                                else
                                                {
                                                    if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.StarTillery, STEng, TRange, cloaker, tmpstarsystem))
                                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                                }
                                            }
                                            else
                                            {
                                                if (capitalobjects < (TM * 4) + 6)
                                                {
                                                    for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                                }
                                                else
                                                {
                                                    if (STs + SSs >= (TM * 8) + 2)
                                                    {
                                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.TechShip, 3, 0, false);
                                                    }
                                                    else
                                                    {
                                                        if (DefendWarships >= mystars / 4)
                                                        {
                                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng3, Random(mindefendwpn, defendwpn - 1), cloaker);
                                                        }
                                                        else
                                                        {
                                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng3, Random(defendwpn, defendwpn + 1), cloaker);
                                                        }
                                                    }
                                                }
                                            }
                                            PrintToDebug("d2", EnD);
                                        }
                                        else if (STs + SSs < TM * 8)
                                        {
                                            //build some scanners to see enemy starships coming
                                            if (sys.Scanners < 5) BuildScanners(sys, 5 - sys.Scanners);
                                            shipi = ClosestStarShip(sys.X, sys.Y, 32767, FindShipFlags.Enemy, ShipKnownFlags.Either);
                                            if (shipi != null)
                                            {
                                                if (MaxSTRange[shipi.OwnerInt] >= TRange - 1)
                                                {
                                                    TRange = MaxSTRange[shipi.OwnerInt] + 2;
                                                    if (TRange > tmprange + 2) TRange = tmprange + 2;
                                                    SRange = TRange + 2;
                                                    if (TRange > 200) TRange = 200;
                                                    if (SRange > 200) SRange = 200;
                                                }
                                            }
                                            if ((STs < 5))
                                            {
                                                if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.StarTillery, STEng, TRange, cloaker, tmpstarsystem))
                                                    for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                            }
                                            else if (_UsefulStarships.ContainsValue(sys.BonusShipType) == true && sys.BonusValue > 0)
                                            {
                                                //BONUS STARSHIP BUILDING!
                                                if (sys.BonusShipType == StarShipType.EMine)
                                                {
                                                    if (capitalobjects < (TM * 2) + 6)
                                                        BuildStarShip(sys, StarShipType.EMine, 1, 0, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                if (sys.BonusShipType == StarShipType.StarTillery)
                                                {
                                                    if (STs <= CountSSs)
                                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if (sys.BonusShipType == StarShipType.SpyShip)
                                                {
                                                    if (CountSSs <= STs)
                                                        BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if (sys.BonusShipType == StarShipType.RepairShip)
                                                {
                                                    if (RSs < (STs + SSs) / 10)
                                                        BuildStarShip(sys, StarShipType.RepairShip, 20, 0, true);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if (sys.BonusShipType == StarShipType.ShieldGenerator)
                                                {
                                                    if (SGs < NumGoodStars)
                                                        BuildStarShip(sys, StarShipType.ShieldGenerator, 20, 0, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if (sys.BonusShipType == StarShipType.CommandShip)
                                                {
                                                    if (CSs < (STs / 2))
                                                        BuildStarShip(sys, StarShipType.CommandShip, 20, SRange, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if (sys.BonusShipType == StarShipType.MadBomb)
                                                {
                                                    if ((SE == true) & (CalAttack == false))
                                                        BuildStarShip(sys, StarShipType.MadBomb, 20, TRange, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if (sys.BonusShipType == StarShipType.CloakDetector)
                                                {
                                                    if (CDs < (STs + SSs) / 10)
                                                        BuildStarShip(sys, StarShipType.CloakDetector, 20, SRange, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if (sys.BonusShipType == StarShipType.BeamShip)
                                                {
                                                    if (MSs < (STs + SSs) / 5)
                                                        BuildStarShip(sys, StarShipType.BeamShip, 20, TRange, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if ((sys.BonusShipType == StarShipType.HijackShip) |
                                                         (sys.BonusShipType == StarShipType.InkSpot) |
                                                         (sys.BonusShipType == StarShipType.Drone))
                                                {
                                                    if (capitalobjects < (TM * 2) + 6)
                                                        BuildStarShip(sys, sys.BonusShipType, wareng3, 0, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if (sys.BonusShipType == StarShipType.MineSweeper)
                                                {
                                                    if ((SE == true) & (CalAttack == false))
                                                    {
                                                        if (_EnemyHasMines[EcapOwner] == true)
                                                            BuildStarShip(sys, StarShipType.MineSweeper, 20, TRange, cloaker);
                                                        else
                                                            goto techshipbuild;
                                                    }
                                                    else
                                                    {
                                                        goto techshipbuild;
                                                    }
                                                }
                                                else if (sys.BonusShipType == StarShipType.BattleStation)
                                                {
                                                    if (BSs < (STs + SSs) / 20)
                                                        BuildStarShip(sys, StarShipType.BattleStation, 6, SRange, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if ((sys.BonusShipType == StarShipType.WarShip) |
                                                         (sys.BonusShipType == StarShipType.Elite) |
                                                         (sys.BonusShipType == StarShipType.DoppleShip))
                                                {
                                                    if ((SE == true) & (CalAttack == false))
                                                        BuildStarShip(sys, sys.BonusShipType, blitzeng, defendwpn + 4, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if (sys.BonusShipType == StarShipType.ParalyShip)
                                                {
                                                    if (PSs < STs)
                                                        BuildStarShip(sys, StarShipType.ParalyShip, 20, TRange, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }
                                                else if (sys.BonusShipType == StarShipType.RemoteViewer)
                                                {
                                                    if (RVs < (SSs / 3))
                                                        BuildStarShip(sys, StarShipType.RemoteViewer, 20, SRange, cloaker);
                                                    else
                                                        goto techshipbuild;
                                                }

                                                goto skiptechshipbuild;
                                            techshipbuild:
                                                {
                                                    // build startillery or spyships if bonus limit is achieved.
                                                    if ((STs <= CountSSs) | (sys != goalstar))
                                                    {
                                                        if ((ParentScanship == null) & (CapitalTask == 1) & (parentspyshipbuilt == false) & (sys == goalstar))
                                                        {
                                                            ad1 = SRange + 5;
                                                            if (ad1 < 20) ad1 = 20;
                                                            if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.SpyShip, 20, ad1, true, tmpstarsystem))
                                                            {
                                                                BuildStarShip(sys, StarShipType.SpyShip, 20, ad1, true);
                                                                parentspyshipbuilt = true;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.StarTillery, 20, TRange, cloaker, tmpstarsystem))
                                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, 20, TRange, cloaker);

                                                        }
                                                    }
                                                    else if (STs > CountSSs && sys == goalstar)
                                                    {
                                                        if ((ParentScanship == null) & (CapitalTask == 1))
                                                        {
                                                            ad1 = SRange + 5;
                                                            if (ad1 < 20) ad1 = 20;
                                                            BuildStarShip(sys, StarShipType.SpyShip, 20, ad1, true);
                                                        }
                                                        else
                                                        {
                                                            if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.SpyShip, 20, SRange, cloaker, tmpstarsystem))
                                                                BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                                        }
                                                    }
                                                }
                                            skiptechshipbuild:
                                                {
                                                    //
                                                }
                                            }
                                            else if ((CountSSs >= STs) | (sys != goalstar))
                                            {
                                                if ((ParentScanship == null) & (CapitalTask == 1) & (parentspyshipbuilt == false) & (sys == goalstar))
                                                {
                                                    ad1 = SRange + 5;
                                                    if (ad1 < 20) ad1 = 20;
                                                    if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.SpyShip, 20, ad1, true, tmpstarsystem))
                                                    {
                                                        BuildStarShip(sys, StarShipType.SpyShip, 20, ad1, true);
                                                        parentspyshipbuilt = true;
                                                    }
                                                }
                                                else
                                                {
                                                    if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.StarTillery, 20, TRange, cloaker, tmpstarsystem))
                                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, 20, TRange, cloaker);

                                                }
                                            }
                                            else if (STs > CountSSs && sys == goalstar)
                                            {
                                                if ((ParentScanship == null) & (CapitalTask == 1))
                                                {
                                                    ad1 = SRange + 5;
                                                    if (ad1 < 20) ad1 = 20;
                                                    BuildStarShip(sys, StarShipType.SpyShip, 20, ad1, true);
                                                }
                                                else
                                                {
                                                    if (sys.Resources >= ShipCostCalculator.GetCost(StarShipType.SpyShip, 20, SRange, cloaker, tmpstarsystem))
                                                        BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                                }
                                            }
                                            PrintToDebug("d3", EnD);
                                        }
                                        else
                                        {
                                            for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.TechShip, 3, 0, false);
                                            PrintToDebug("d4", EnD);
                                        }
                                    }
                                    #endregion
                                }
                                else if (sys.Value >= 6 && sys.Value < 12)
                                {
                                    #region MidStar
                                    PrintToDebug("midvalue", EnD);
                                    if (((_StarCovered[sys.Name] == false) | (sys.Scanners < tmprange)) & (_ExpandOrder[sys.Name] == false) &
                                        (Expand == false) & (STs >= 2) & (_MyBorderScan[sys.Name] == true) & (Estar1 != null))
                                        BuildScanners(sys, 5);
                                    if (cloaker == true)
                                    {
                                        if ((_MyBorderScan[sys.Name] == true) & (sys.Resources < (TM * 50)))
                                            for (int d = 0; d < 8; d++)
                                                BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, cloaker);
                                    }
                                    if ((eDefend == true) & (_ExpandOrder[sys.Name] == false))
                                    {
                                        BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, cloaker); //
                                        BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                        for (int d = 0; d < 2; d++)
                                        {
                                            enemyhasstartillery = PlayerHasStartillery[Eship2.OwnerInt];
                                            if (sys.Resources > (TM * 5) + 15)
                                            {
                                                if (enemyhasstartillery == false)
                                                    BuildStarShip(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                                else
                                                    BuildStarShip(sys, StarShipType.Drone, Random(wareng1, wareng2), 0, cloaker);
                                            }
                                            else
                                            {
                                                if (enemyhasstartillery == false)
                                                    BuildStarShip(sys, StarShipType.Drone, Random(wareng1, wareng2), 0, cloaker);
                                                else
                                                    BuildStarShip(sys, StarShipType.Drone, Random(wareng0, wareng1), 0, cloaker);
                                            }
                                            if (sys.Value <= 9)
                                            {
                                                if (enemyhasstartillery == false)
                                                    BuildStarShip(sys, StarShipType.Drone, Random(wareng0, wareng1), 0, cloaker);
                                                else
                                                    BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, true);
                                            }
                                            else
                                            {
                                                if (eBuild == true) BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, cloaker);
                                                if (cloaker == true) BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, cloaker);
                                                if (enemyhasstartillery == false)
                                                    BuildStarShip(sys, StarShipType.Drone, Random(wareng1, wareng2), 0, cloaker);
                                                else
                                                    BuildStarShip(sys, StarShipType.Drone, Random(wareng0, wareng1), 0, cloaker);
                                            }
                                        }
                                    }
                                    if ((CapAlert == 2) & (sys.Value >= 10) & (Distance(sys.X, sys.Y, mycapx, mycapy) <= 15))
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                    }
                                    if ((Estar2 != null) | (_ExpandOrder[sys.Name] == true) | (AttackWarships + SearchWarships < ((targets / ((TM * 1.4) + 0.6)) + 1)))
                                    {
                                        ad1 = Random(minwarshipwpn, defendwpn - 1);
                                        SetAutoStarShipType(sys, StarShipType.WarShip, expeng, ad1, cloaker);
                                        SetAutoStarShip(sys, true);
                                        PrintToDebug("d1", EnD);
                                    }
                                    else if (_UsefulStarships.ContainsValue(sys.BonusShipType) == true)
                                    {
                                        //BONUS STARSHIP BUILDING!
                                        if (sys.BonusShipType == StarShipType.EMine)
                                        {
                                            if (capitalobjects < (TM * 2) + 6)
                                                BuildStarShip(sys, StarShipType.EMine, 1, 0, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        if (sys.BonusShipType == StarShipType.StarTillery)
                                        {
                                            if (STs <= CountSSs)
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, STEng, TRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.SpyShip)
                                        {
                                            if (CountSSs <= STs)
                                                BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.RepairShip)
                                        {
                                            if (RSs < (STs + SSs) / 10)
                                                BuildStarShip(sys, StarShipType.RepairShip, 20, 0, true);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.ShieldGenerator)
                                        {
                                            if (SGs < NumGoodStars)
                                                BuildStarShip(sys, StarShipType.ShieldGenerator, 20, 0, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.CommandShip)
                                        {
                                            if (CSs < (STs / 2))
                                                BuildStarShip(sys, StarShipType.CommandShip, 20, SRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.MadBomb)
                                        {
                                            if ((SE == true) & (CalAttack == false))
                                                BuildStarShip(sys, StarShipType.MadBomb, 20, TRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.CloakDetector)
                                        {
                                            if (CDs < (STs + SSs) / 10)
                                                BuildStarShip(sys, StarShipType.CloakDetector, 20, SRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.BeamShip)
                                        {
                                            if (MSs < (STs + SSs) / 5)
                                                BuildStarShip(sys, StarShipType.BeamShip, 20, TRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if ((sys.BonusShipType == StarShipType.HijackShip) |
                                                 (sys.BonusShipType == StarShipType.InkSpot) |
                                                 (sys.BonusShipType == StarShipType.Drone))
                                        {
                                            if (capitalobjects < (TM * 2) + 6)
                                                BuildStarShip(sys, sys.BonusShipType, wareng3, 0, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.MineSweeper)
                                        {
                                            if ((SE == true) & (CalAttack == false))
                                            {
                                                if (_EnemyHasMines[EcapOwner] == true)
                                                    BuildStarShip(sys, StarShipType.MineSweeper, 20, TRange, cloaker);
                                                else
                                                    goto techshipbuild;
                                            }
                                            else
                                            {
                                                goto techshipbuild;
                                            }
                                        }
                                        else if (sys.BonusShipType == StarShipType.BattleStation)
                                        {
                                            if (BSs < (STs + SSs) / 20)
                                                BuildStarShip(sys, StarShipType.BattleStation, 6, SRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if ((sys.BonusShipType == StarShipType.WarShip) |
                                                 (sys.BonusShipType == StarShipType.Elite) |
                                                 (sys.BonusShipType == StarShipType.DoppleShip))
                                        {
                                            if ((SE == true) & (CalAttack == false))
                                                BuildStarShip(sys, sys.BonusShipType, blitzeng, defendwpn + 4, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.ParalyShip)
                                        {
                                            if (PSs < STs)
                                                BuildStarShip(sys, StarShipType.ParalyShip, 20, TRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.RemoteViewer)
                                        {
                                            if (RVs < (SSs / 3))
                                                BuildStarShip(sys, StarShipType.RemoteViewer, 20, SRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }

                                        goto skiptechshipbuild;
                                    techshipbuild:
                                        {
                                            // build other starships.
                                            if ((TM < 12) & (Estar2 == null))
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.TechShip, 3, 0, false);
                                            }
                                            else if ((SE == true) & (Estar2 == null) & (CalAttack == false))
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, blitzeng, defendwpn + 4, cloaker);
                                            }
                                            else if ((DefendWarships < mystars / 4) & (Estar2 == null))
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                            }
                                            else if ((Estar2 == null) & (capitalobjects < TM * 5))
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, defendwpn, cloaker);
                                            }
                                            else
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng2, defendwpn - 1, cloaker);
                                            }
                                        }
                                    skiptechshipbuild:
                                        {
                                            //
                                        }
                                        PrintToDebug("d2", EnD);
                                    }
                                    else if ((TM < 12) & (Estar2 == null))
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.TechShip, 3, 0, false);
                                        PrintToDebug("d3", EnD);
                                    }
                                    else if ((SE == true) & (Estar2 == null) & (CalAttack == false))
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, blitzeng, defendwpn + 4, cloaker);
                                        PrintToDebug("d4", EnD);
                                    }
                                    else if ((DefendWarships < mystars / 4) & (Estar2 == null))
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                        PrintToDebug("d5", EnD);
                                    }
                                    else if ((Estar2 == null) & (capitalobjects < TM * 5))
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.Drone, wareng3, defendwpn, cloaker);
                                        PrintToDebug("d6", EnD);
                                    }
                                    else
                                    {
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng2, defendwpn - 1, cloaker);
                                        PrintToDebug("d7", EnD);
                                    }
                                    #endregion
                                }
                                else if (sys.Value < 6)
                                {
                                    #region SmallStar
                                    PrintToDebug("smallvalue", EnD);
                                    if (eDefend == true)
                                    {
                                        BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                        for (int d = 0; d < 2; d++)
                                        {
                                            enemyhasstartillery = PlayerHasStartillery[Eship2.OwnerInt];
                                            if (eBuild == true) BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, cloaker);
                                            if (enemyhasstartillery == false)
                                                BuildStarShip(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                            else
                                                BuildStarShip(sys, StarShipType.Drone, Random(wareng1, wareng2), 0, cloaker);
                                            BuildStarShip(sys, StarShipType.Drone, Random(wareng1, wareng2), 0, cloaker);
                                            if (enemyhasstartillery == false)
                                                BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, cloaker);
                                            else
                                                BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, true);
                                        }
                                    }
                                    if (Estar3 != null)
                                    {
                                        PrintToDebug("d1", EnD);
                                        ad1 = Random(minwarshipwpn, defendwpn - 1);
                                        SetAutoStarShipType(sys, StarShipType.WarShip, expeng, ad1, cloaker);
                                        SetAutoStarShip(sys, true);
                                    }
                                    else if (_UsefulStarships.ContainsValue(sys.BonusShipType) == true)
                                    {
                                        PrintToDebug("d2", EnD);
                                        //BONUS STARSHIP BUILDING!
                                        if (sys.BonusShipType == StarShipType.EMine)
                                        {
                                            if (capitalobjects < (TM * 2) + 6)
                                                BuildStarShip(sys, StarShipType.EMine, 1, 0, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        if (sys.BonusShipType == StarShipType.StarTillery)
                                        {
                                            if (STs <= CountSSs)
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.StarTillery, 20, TRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.SpyShip)
                                        {
                                            if (CountSSs <= STs)
                                                BuildStarShip(sys, StarShipType.SpyShip, 20, SRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.RepairShip)
                                        {
                                            if (RSs < (STs + SSs) / 10)
                                                BuildStarShip(sys, StarShipType.RepairShip, 20, 0, true);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.ShieldGenerator)
                                        {
                                            if (SGs < NumGoodStars)
                                                BuildStarShip(sys, StarShipType.ShieldGenerator, 20, 0, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.CommandShip)
                                        {
                                            if (CSs < (STs / 2))
                                                BuildStarShip(sys, StarShipType.CommandShip, 20, SRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.MadBomb)
                                        {
                                            if ((SE == true) & (CalAttack == false))
                                                BuildStarShip(sys, StarShipType.MadBomb, 20, TRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.CloakDetector)
                                        {
                                            if (CDs < (STs + SSs) / 10)
                                                BuildStarShip(sys, StarShipType.CloakDetector, 20, SRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.BeamShip)
                                        {
                                            if (MSs < (STs + SSs) / 5)
                                                BuildStarShip(sys, StarShipType.BeamShip, 20, TRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if ((sys.BonusShipType == StarShipType.HijackShip) |
                                                 (sys.BonusShipType == StarShipType.InkSpot) |
                                                 (sys.BonusShipType == StarShipType.Drone))
                                        {
                                            if (capitalobjects < (TM * 2) + 6)
                                                BuildStarShip(sys, sys.BonusShipType, wareng3, 0, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.MineSweeper)
                                        {
                                            if ((SE == true) & (CalAttack == false))
                                            {
                                                if (_EnemyHasMines[EcapOwner] == true)
                                                    BuildStarShip(sys, StarShipType.MineSweeper, 20, TRange, cloaker);
                                                else
                                                    goto techshipbuild;
                                            }
                                            else
                                            {
                                                goto techshipbuild;
                                            }
                                        }
                                        else if (sys.BonusShipType == StarShipType.BattleStation)
                                        {
                                            if (BSs < (STs + SSs) / 20)
                                                BuildStarShip(sys, StarShipType.BattleStation, 6, SRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if ((sys.BonusShipType == StarShipType.WarShip) |
                                                 (sys.BonusShipType == StarShipType.Elite) |
                                                 (sys.BonusShipType == StarShipType.DoppleShip))
                                        {
                                            if ((SE == true) & (CalAttack == false))
                                                BuildStarShip(sys, sys.BonusShipType, blitzeng, defendwpn + 4, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.ParalyShip)
                                        {
                                            if (PSs < STs)
                                                BuildStarShip(sys, StarShipType.ParalyShip, 20, TRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }
                                        else if (sys.BonusShipType == StarShipType.RemoteViewer)
                                        {
                                            if (RVs < (SSs / 3))
                                                BuildStarShip(sys, StarShipType.RemoteViewer, 20, SRange, cloaker);
                                            else
                                                goto techshipbuild;
                                        }

                                        goto skiptechshipbuild;
                                    techshipbuild:
                                        {
                                            // build other starships.
                                            if (TM < 25)
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.TechShip, 3, 0, false);
                                            }
                                            else if (DefendWarships < mystars / 4)
                                            {
                                                for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                            }
                                            else
                                            {
                                                if (Random(0, 100) > 70)
                                                    BuildStarShip(sys, StarShipType.InkSpot, wareng2, 0, cloaker);
                                                else
                                                    BuildStarShip(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                            }
                                        }
                                    skiptechshipbuild:
                                        {
                                            //
                                        }

                                    }
                                    else if (TM < 25)
                                    {
                                        PrintToDebug("d3", EnD);
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.TechShip, 3, 0, false);
                                    }
                                    else if (DefendWarships < mystars / 4)
                                    {
                                        PrintToDebug("d4", EnD);
                                        for (int d = 0; d < 8; d++) BuildStarShip(sys, StarShipType.WarShip, wareng3, defendwpn, cloaker);
                                    }
                                    else
                                    {
                                        PrintToDebug("d5", EnD);
                                        if (Random(0, 100) > 70)
                                            BuildStarShip(sys, StarShipType.InkSpot, wareng2, 0, cloaker);
                                        else
                                            BuildStarShip(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                    }
                                    #endregion
                                }
                            }
                            #region Shield Defense Code
                            if (largewarning == true)
                            {
                                if (sys.Resources >= (TM * 9) + 9)
                                    SetAutoStarShipType(sys, StarShipType.Drone, wareng3, 0, cloaker);
                                else if (sys.Resources >= TM + 9)
                                    SetAutoStarShipType(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                else
                                    SetAutoStarShipType(sys, StarShipType.Drone, wareng1, 0, cloaker);
                                SetAutoStarShip(sys, true);
                            }
                            if (eBuild == true)
                            {
                                if (sys != mycap) BuildStarShip(sys, StarShipType.InkSpot, wareng0, 0, cloaker); //
                                if (SE == true)
                                {
                                    if (Distance(sys.X, sys.Y, Ecapx, Ecapy) <= 10 && sys == mycap)
                                        SetAutoStarShipType(sys, StarShipType.WarShip, wareng0, 2, cloaker);
                                    else
                                    {
                                        BuildShields(sys, TM + 5); //
                                        SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                    }
                                }
                                else
                                {
                                    BuildShields(sys, TM + 5); //
                                    SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                }
                                SetAutoStarShip(sys, true);
                            }
                            if (eDefend == true)
                            {
                                if (SE == true)
                                {
                                    if (Distance(sys.X, sys.Y, Ecapx, Ecapy) <= 10 && sys == mycap && closecombatmode == true)
                                    {
                                        if ((sys.Shields <= 5))
                                        {
                                            if (mystars <= 1)
                                            {
                                                if (sys.Resources >= (TM * 6) + 6)
                                                    SetAutoStarShipType(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                                else
                                                    SetAutoStarShipType(sys, StarShipType.WarShip, wareng0, 2, cloaker);
                                            }
                                            else
                                            {
                                                SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                            }
                                        }
                                        else
                                        {
                                            if (sys.Resources >= (TM * 6) + 6)
                                                SetAutoStarShipType(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                            else
                                                SetAutoStarShipType(sys, StarShipType.WarShip, wareng1, defendwpn - 3, cloaker);
                                        }
                                    }
                                    else
                                    {
                                        if (sys.IsCapital == true)
                                        {
                                            if (closecombatmode == true)
                                            {
                                                if (mystars <= 1)
                                                {
                                                    if (sys.Resources >= (TM * 6) + 6)
                                                        SetAutoStarShipType(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                                    else
                                                        SetAutoStarShipType(sys, StarShipType.WarShip, wareng1, 2, cloaker);
                                                }
                                                else
                                                {
                                                    SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                                }
                                            }
                                            else
                                            {
                                                if (mystars <= 1)
                                                {
                                                    if (sys.Resources >= (TM * 6) + 6)
                                                        SetAutoStarShipType(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                                    else
                                                        SetAutoStarShipType(sys, StarShipType.WarShip, wareng0, 2, cloaker);
                                                }
                                                else
                                                {
                                                    SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                                }
                                            }
                                        }
                                        else if (sys.Value >= 12)
                                        {
                                            if (sys.Resources > (TM * 2) + 10)
                                                SetAutoStarShipType(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                            else
                                                SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                        }
                                        else if (sys.Value >= 6)
                                        {
                                            if (sys.Resources > (TM * 2) + 10)
                                                SetAutoStarShipType(sys, StarShipType.Drone, wareng1, 0, cloaker);
                                            else
                                                SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                        }
                                        else
                                        {
                                            SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                        }
                                    }
                                }
                                else
                                {
                                    if (sys.Value >= 12)
                                    {
                                        if (sys.Resources > (TM * 2) + 10)
                                            SetAutoStarShipType(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                        else
                                            SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                    }
                                    else if (sys.Value >= 6)
                                    {
                                        if (sys.Resources > (TM * 2) + 10)
                                            SetAutoStarShipType(sys, StarShipType.Drone, wareng1, 0, cloaker);
                                        else
                                            SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                    }
                                    else
                                    {
                                        SetAutoStarShipType(sys, StarShipType.Drone, wareng0, 0, cloaker);
                                    }
                                }
                                SetAutoStarShip(sys, true);
                            }
                            if (closecombatstart == true)
                            {
                                SetAutoStarShipType(sys, StarShipType.Drone, wareng2, 0, cloaker);
                                SetAutoStarShip(sys, true);
                            }
                            #endregion
                            PrintToDebug("eBuild=" + eBuild.ToString() + " eDefend=" + eDefend.ToString() + " Attacks=" + _GetStarAttacks[sys.Name].ToString() + " Name=" + sys.Name, EnD);
                            if (_ExpandOrder[sys.Name] == true)
                                _ExpandOrder[sys.Name] = false;
                        }
                        s = s + 1;
                    }
                    #endregion

                    PrintToDebug("--------Order Starships--------", EnD);

                    //Note in SV6.0, Uncomment the code described above each starship section
                    #region Order Starships
                    //Finally! Order Starships.
                    #region Variables
                    bool cancelorder = false;
                    int damagedstarships = 0;
                    int attackws = 0;
                    int searchws = 0;
                    bool drattackstarship = false;
                    int meleewarships = 0;
                    int wtask = 0;
                    int[] wshighest = new int[3];
                    double[] wsclosest = new double[3];
                    StarSystemInfo[] wstarget = new StarSystemInfo[3];
                    int[] defendslope = new int[9];
                    int gshields = 0;
                    defendslope[8] = 0;
                    int stargetx = 0;
                    int stargety = 0;
                    bool shipdamaged = false;
                    double shiphealth = 100;
                    bool basefriendlystar = true;
                    bool attackstarship = false;
                    int engagethreshold = 0;
                    bool escortstarship = false;
                    double diffx = 0;
                    double diffy = 0;
                    //double bonusadd = 0;
                    int bonusint = 0;
                    double stardist = 0;
                    double shipdist = 0;
                    int intclosestst = 99999;
                    int intcloseststb = 99999;
                    int ENRange = 0;
                    int intDSDistb = 0;
                    int orderx = 0;
                    int ordery = 0;
                    bool attcancel = false;
                    bool beamattackstarship = false;
                    bool bmshipcancel = false;
                    int destx = 0;
                    int desty = 0;
                    bool starselected = false;
                    double tantar = 0;
                    StarShipInfo beamattackobject = null;
                    StarSystemInfo tarStar1 = null;
                    StarSystemInfo tarStar2 = null;
                    StarSystemInfo tarStar3 = null;
                    StarSystemInfo tarStar4 = null;
                    StarSystemInfo tarStar5 = null;
                    StarSystemInfo tarStar6 = null;
                    StarSystemInfo star3a = null;
                    StarSystemInfo star3b = null;
                    StarShipInfo tarShip1 = null;
                    StarShipInfo tarShip2 = null;
                    WormholeInfo whobject = null;
                    PulsarInfo pultarget = null;
                    int wmuselimit = 10;
                    Dictionary<WormholeInfo,int> wormholeusage = new Dictionary<WormholeInfo,int>();
                    s = 0;
                    foreach (WormholeInfo wminfo in Wormholes)
                    {
                        if (wormholeusage.ContainsKey(wminfo) == false)
                            wormholeusage.Add(wminfo,0);
                        wormholeusage[wminfo] = 0;
                        s = s + 1;
                    }
                    #endregion

                    s = 0;
                    foreach (StarShipInfo ship in MyStarShips)
                    {
                        if (ship.OwnedByMe == true)
                        {
                            if ((ship.ShipType == StarShipType.WarShip) | (ship.ShipType == StarShipType.DoppleShip) | (ship.ShipType == StarShipType.Elite))
                            {
                                #region Warship Target Code
                                //Assign which task this warship is on

                                #region Assignment Code
                                if (_shipTask.ContainsKey(ship.Code) == false)
                                {
                                    wtask = 1;
                                    if (ship.Value < defendwpn)
                                    {
                                        attackws++;
                                        if ((attackws > searchws * 5) & (searchws < unknowns / 4) & (attackws > 5))
                                        {
                                            attackws--;
                                            searchws++;
                                            wtask = 2;
                                        }
                                    }
                                    else if ((ship.Value >= defendwpn) & ((ship.Value < cavalrywpn) | (SE == false)))
                                    {
                                        wtask = 3;
                                    }
                                    else if (ship.Value >= cavalrywpn)
                                    {
                                        wtask = 4;
                                    }
                                    _shipTask.Add(ship.Code, wtask);
                                }
                                else
                                {
                                    if (ship.Value < defendwpn)
                                    {
                                        attackws++;
                                        if ((attackws > searchws * 5) & (searchws < unknowns / 4) & (attackws > 5))
                                        {
                                            attackws--;
                                            searchws++;
                                        }
                                    }
                                }
                                #endregion

                                //Begin Orders
                                if (_shipTask[ship.Code] == 1)
                                {
                                    #region Normal Offensive Target Code
                                    PrintToDebug("WS1 " + ship.Code, EnD);
                                    if (((ship.Value <= 3) & (Expand == false) & (ship.Engines > wareng1)) | ((ship.Value <= mindefendwpn) & (Expand == true) & (ship.Engines > wareng1)))
                                        AttackAdjacent(ship, false);
                                    else
                                        AttackAdjacent(ship, true);
                                    //Check to see if I already have an order
                                    if (_shipTargetOrder.ContainsKey(ship.Code) == false)
                                        _shipTargetOrder.Add(ship.Code, null);
                                    if (_shipTargetOrder[ship.Code] != null)
                                    {
                                        if ((_shipTargetOrder[ship.Code].OwnedByMe == true) |
                                            (AlliedWith(_shipTargetOrder[ship.Code].Owner) != AllianceLevel.None) |
                                            (AlliedWithMe(_shipTargetOrder[ship.Code].Owner) != AllianceLevel.None))
                                        {
                                            cancelorder = false;
                                            for (int j = 0; j < targets; j++)
                                            {
                                                if (_PlayerOrder.ContainsKey("Take" + TStar[j].Name) == true)
                                                    cancelorder = true;
                                                if (TStar[j].IsCapital == true)
                                                    if (_PlayerOrder.ContainsKey("Conquer" + TStar[j].Owner) == true)
                                                        cancelorder = true;
                                            }
                                            if (cancelorder == false)
                                            {
                                                _shipTargetOrder[ship.Code] = null;
                                            }
                                        }
                                        if (_shipTargetOrder[ship.Code] != null)
                                        {
                                            //reassign target if a nearby unconquered star is way faster to get to than the assigned target
                                            stari = ClosestStarSystem(ship.X, ship.Y, 20, FindSystemFlags.Unfriendly);
                                            if (stari != null)
                                                if (DistanceQuick(stari.X, stari.Y, ship.X, ship.Y) * 4 <= DistanceQuick(_shipTargetOrder[ship.Code].X, _shipTargetOrder[ship.Code].Y, ship.X, ship.Y))
                                                    _shipTargetOrder[ship.Code] = stari;
                                            //Cancel orders that are considered overkill for this expand mode
                                            if ((Expand == true) & (_TShields[_shipTargetOrder[ship.Code].Name] < -1))
                                            {
                                                if (_shipTargetOrder[ship.Code].OwnerInt == -1)
                                                    _shipTargetOrder[ship.Code] = null;
                                            }
                                            else if ((Expand == false) & (_TShields[_shipTargetOrder[ship.Code].Name] < 0 - (defendwpn * 3)))
                                            {
                                                _shipTargetOrder[ship.Code] = null;
                                            }
                                        }
                                    }

                                    if (_shipTargetOrder[ship.Code] == null)
                                    {
                                        //warship has no order so find the best target to hit.
                                        for (int d = 0; d < 3; d++)
                                        {
                                            wsclosest[d] = 32767.9;
                                            wshighest[d] = -999;
                                            wstarget[d] = null;
                                        }
                                        i = 0;
                                        ad = 0;
                                        while (i < targets)
                                        {
                                            cancelorder = false;
                                            stari = TStar[i];
                                            if (_PlayerOrder.ContainsKey("Take" + stari.Name) == true)
                                                cancelorder = true;
                                            if (stari.IsCapital == true)
                                                if (_PlayerOrder.ContainsKey("Conquer" + stari.Owner) == true)
                                                    cancelorder = true;
                                            floArcdist = Distance(ship.X, ship.Y, stari.X, stari.Y);
                                            gshields = _TShields[stari.Name];
                                            if (gshields < 0) gshields = 0;
                                            bonusint = _GetStarTValue[stari.Name];
                                            if ((AlliedWith(stari.Owner) == AllianceLevel.None) |
                                                (AlliedWithMe(stari.Owner) == AllianceLevel.None) | cancelorder == true)
                                            {
                                                if ((Expand == true) & (_TShields[stari.Name] >= -1))
                                                {
                                                    if ((mystars < 5 && _LastStarOwner[stari.Name] <= 0) | (mystars >= 5))
                                                    {
                                                        if (ship.Value == gshields + 1)
                                                        {
                                                            if (wshighest[0] < bonusint)
                                                            {
                                                                wshighest[0] = bonusint;
                                                                wstarget[0] = stari;
                                                            }
                                                        }
                                                        else if ((ship.Value > gshields + 1) & (_TShields[stari.Name] >= 0))
                                                        {
                                                            if (wshighest[1] <= bonusint)
                                                            {
                                                                wshighest[1] = bonusint;
                                                                wstarget[1] = stari;
                                                            }
                                                        }
                                                        else if (ship.Value < _TShields[stari.Name] + 1)
                                                        {
                                                            if (wsclosest[2] > floArcdist)
                                                            {
                                                                wsclosest[2] = floArcdist;
                                                                wstarget[2] = stari;
                                                            }
                                                        }
                                                    }
                                                }
                                                else if ((Expand == false) & (_TShields[stari.Name] >= 0 - (defendwpn * 3)))
                                                {
                                                    if (SE == false)
                                                    {
                                                        if (floArcdist < wsclosest[2])
                                                        {
                                                            wsclosest[2] = floArcdist;
                                                            wstarget[2] = stari;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (floArcdist < wsclosest[2])
                                                        {
                                                            if ((mystars >= 1) | (stari.IsCapital == false))
                                                            {
                                                                if (floArcdist < Distance(ship.X, ship.Y, Ecapx, Ecapy) / 1.3)
                                                                {
                                                                    wsclosest[2] = floArcdist;
                                                                    wstarget[2] = stari;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            i = i + 1;
                                        }
                                        if ((SE == true) & (Expand == false) & (wstarget[2] == null) & (mystars >= 1))
                                        {
                                            wstarget[2] = Ecap;
                                        }
                                        stari = ClosestStarSystem(ship.X, ship.Y, 20, FindSystemFlags.Unfriendly);
                                        if (wstarget[0] == null) wstarget[0] = wstarget[1];
                                        if (wstarget[0] == null) wstarget[0] = wstarget[2];
                                        if ((wstarget[0] == null) | ((stari != null) & (Expand == false)))
                                        {
                                            if (stari != null)
                                            {
                                                //null stari if not within range
                                                if (((ship.X - 10 <= stari.X) & (ship.Y - 10 <= stari.Y) & (ship.X + 10 >= stari.X) & (ship.Y + 10 >= stari.Y)) == false)
                                                    stari = null;
                                                //null stari if not owned by enemy
                                                if (stari != null)
                                                    if (_LastStarOwner[stari.Name] != 1)
                                                        stari = null;
                                                //null stari if warships has already targeted it
                                                if (stari != null)
                                                    if (_TShields[stari.Name] < -5)
                                                        stari = null;
                                                //null stari if the star is a capital and I don't have any stars
                                                if (stari != null)
                                                    if ((mystars < 1) & (stari.IsCapital == true))
                                                        stari = null;
                                            }
                                            if (stari != null)
                                            {
                                                wstarget[0] = stari;
                                                _shipTargetOrder[ship.Code] = wstarget[0];
                                                _TShields[wstarget[0].Name] = _TShields[wstarget[0].Name] - ship.Value;
                                            }
                                            else if (wstarget[0] != null)
                                            {
                                                _shipTargetOrder[ship.Code] = wstarget[0];
                                                _TShields[wstarget[0].Name] = _TShields[wstarget[0].Name] - ship.Value;
                                            }
                                            else
                                            {
                                                wstarget[0] = ClosestStarSystem(ship.X, ship.Y, 32767, FindSystemFlags.Unfriendly);
                                                _TShields[wstarget[0].Name] = _TShields[wstarget[0].Name] - ship.Value;
                                            }
                                        }
                                        else
                                        {
                                            _TShields[wstarget[0].Name] = _TShields[wstarget[0].Name] - ship.Value;
                                            _shipTargetOrder[ship.Code] = wstarget[0];
                                        }
                                        if (wstarget[0] != null)
                                        {
                                            whobject = WormHoleWayFaster(ship, wstarget[0].X, wstarget[0].Y);
                                            if (whobject != null)
                                            {
                                                if (wormholeusage[whobject] <= wmuselimit)
                                                {
                                                    wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                    Move(ship, whobject.X, whobject.Y);
                                                }
                                                else
                                                {
                                                    if (_WarshipWeaponsNearStar[wstarget[0].Name] > _LastKnownShields[wstarget[0].Name])
                                                        Target(ship, wstarget[0]);
                                                    else
                                                        Move(ship, wstarget[0].X, wstarget[0].Y);
                                                }
                                            }
                                            else
                                            {
                                                if (_WarshipWeaponsNearStar[wstarget[0].Name] > _LastKnownShields[wstarget[0].Name])
                                                    Target(ship, wstarget[0]);
                                                else
                                                    Move(ship, wstarget[0].X, wstarget[0].Y);
                                            }
                                        }
                                        if (wstarget[0].OwnerInt > -1 && wstarget[0].OwnedByMe == false)
                                        {
                                            if (IsAdjacentToCoords(ship, wstarget[0].X, wstarget[0].Y) == true)
                                                AttackAdjacent(ship, false);
                                        }

                                        if (_WarshipWeaponsNearStar[wstarget[0].Name] > _LastKnownShields[wstarget[0].Name])
                                            PrintToDebug("WS1 " + ship.Code + " attacking starsystem " + wstarget[0].Name, EnD);
                                        else
                                            PrintToDebug("WS1 " + ship.Code + " heading to starsystem " + wstarget[0].Name, EnD);
                                    }
                                    else
                                    {
                                        //warship already has an order so target the targeted starsystem. If there is an enemy star near the warship, retarget warship to it.
                                        wstarget[0] = _shipTargetOrder[ship.Code];
                                        stari = ClosestStarSystem(ship.X, ship.Y, 6, FindSystemFlags.Enemy);
                                        if (stari != null)
                                        {
                                            if ((stari.OwnerInt > -1) & (stari.Value > 0))
                                                if ((mystars >= 2) | (stari.IsCapital == false))
                                                    wstarget[0] = stari;
                                        }

                                        //Determine if there is a better star nearby to target than the one we are on right now
                                        starselected = false;
                                        tarStar6 = null;
                                        if (_WarshipWeaponsNearStar[wstarget[0].Name] <= _LastKnownShields[wstarget[0].Name])
                                        {
                                            //if the star is known and unowned then find any known targets that can be conquered
                                            if (_LastStarOwner[wstarget[0].Name] == 0)
                                            {
                                                for (int j = 0; j < targets; j++)
                                                {
                                                    stari = TStar[j];
                                                    if (stari.OwnedByMe == false && _TShields[stari.Name] > -1)
                                                        if (_WarshipWeaponsNearStar[stari.Name] > _TShields[stari.Name] && _LastStarOwner[stari.Name] <= 0)
                                                            if (((Expand == true) & (stari.IsCapital == false)) | (Expand == false))
                                                                if ((mystars >= 1) | (stari.IsCapital == false))
                                                                    if (Distance(ship.X, ship.Y, stari.X, stari.Y) <= ((double)ship.Engines * 2.5))
                                                                    {
                                                                        tarStar6 = stari;
                                                                        starselected = true;
                                                                    }
                                                }
                                            }
                                        }
                                        if (starselected == true)
                                        {
                                            _WarshipWeaponsNearStar[wstarget[0].Name] = _WarshipWeaponsNearStar[wstarget[0].Name] - ship.Value;
                                            wstarget[0] = tarStar6;
                                            _shipTargetOrder[ship.Code] = tarStar6;
                                        }

                                        //Process Order
                                        _TShields[wstarget[0].Name] = _TShields[wstarget[0].Name] - ship.Value;
                                        if (wstarget[0] != null)
                                        {
                                            whobject = WormHoleWayFaster(ship, wstarget[0].X, wstarget[0].Y);
                                            if (whobject != null)
                                            {
                                                if (wormholeusage[whobject] <= wmuselimit)
                                                {
                                                    wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                    Move(ship, whobject.X, whobject.Y);
                                                }
                                                else
                                                {
                                                    if (_WarshipWeaponsNearStar[wstarget[0].Name] > _LastKnownShields[wstarget[0].Name])
                                                        Target(ship, wstarget[0]);
                                                    else
                                                        Move(ship, wstarget[0].X, wstarget[0].Y);
                                                }
                                            }
                                            else
                                            {
                                                if (_WarshipWeaponsNearStar[wstarget[0].Name] > _LastKnownShields[wstarget[0].Name])
                                                    Target(ship, wstarget[0]);
                                                else
                                                    Move(ship, wstarget[0].X, wstarget[0].Y);
                                            }
                                        }

                                        //Deactivate attack adjacent if next to an opponent's star
                                        if (wstarget[0].OwnerInt > -1 && wstarget[0].OwnedByMe == false)
                                        {
                                            if (IsAdjacentToCoords(ship, wstarget[0].X, wstarget[0].Y) == true)
                                                AttackAdjacent(ship, false);
                                        }
                                        if (_WarshipWeaponsNearStar[wstarget[0].Name] > _LastKnownShields[wstarget[0].Name])
                                            PrintToDebug("WS1 " + ship.Code + " already attacking starsystem " + wstarget[0].Name, EnD);
                                        else
                                            PrintToDebug("WS1 " + ship.Code + " already heading to starsystem " + wstarget[0].Name, EnD);
                                        
                                    }
                                    //battleststions pose a big threat to Stratego 4s drone defenses so allow the warships to attack a nearby one.
                                    StarShipInfo battlese = null;
                                    battlese = ClosestStarShip(ship.X,ship.Y,20, FindShipFlags.Enemy, ShipKnownFlags.Known);
                                    if (battlese != null)
                                        if (battlese.ShipType == StarShipType.BattleStation)
                                            if (_shipTargetOrder[ship.Code] != null)
                                                if (DistanceQuick(battlese.X, battlese.Y, ship.X, ship.Y) <= DistanceQuick(_shipTargetOrder[ship.Code].X, _shipTargetOrder[ship.Code].Y, ship.X, ship.Y) / 2)
                                                    Target(ship, battlese);
                                    #endregion
                                }
                                else if (_shipTask[ship.Code] == 2)
                                {
                                    #region Search Target Code
                                    PrintToDebug("WS2 " + ship.Code, EnD);
                                    //search warships
                                    AttackAdjacent(ship, false);

                                    //Check to see if I already have an order
                                    if (_shipTargetOrder.ContainsKey(ship.Code) == false)
                                        _shipTargetOrder.Add(ship.Code, null);

                                    if (_shipTargetOrder[ship.Code] != null)
                                    {
                                        stari = _shipTargetOrder[ship.Code];
                                        if (stari.Visible == true)
                                        {
                                            ad1 = ship.Engines + (int)(ship.Value * 1.5);
                                            ad2 = Convert.ToInt32(stari.Value + (stari.Resources / 1.5) + (stari.Scanners / 5));
                                            ad3 = _TShields[stari.Name];
                                            if ((_TAValue[stari.Name] > ad3) & (ad1 <= ad2))
                                            {
                                                if ((AlliedWith(stari.Owner) != AllianceLevel.None) |
                                                    (AlliedWithMe(stari.Owner) != AllianceLevel.None))
                                                {
                                                    _shipTargetOrder[ship.Code] = null;
                                                }
                                                else
                                                {
                                                    PrintToDebug("WS2 " + ship.Code + " has switched to task 1 and attacked star.", EnD);
                                                    _TShields[stari.Name] = -999;
                                                    Target(ship, stari);
                                                    _shipTargetOrder[ship.Code] = stari;
                                                    _shipTask[ship.Code] = 1;
                                                    //SendMessage(ChatChannel.All, "WarShip " + ship.Code + " has targeted " + stari.Name);
                                                }
                                            }
                                            else
                                            {
                                                _shipTargetOrder[ship.Code] = null;
                                            }
                                        }
                                    }

                                    PrintToDebug("WS2 " + ship.Code + " processing search", EnD);

                                    if ((_shipTargetOrder[ship.Code] == null) & (_shipTask[ship.Code] == 2))
                                    {
                                        wsclosest[0] = 32767;
                                        wstarget[0] = null;
                                        i = 0;
                                        while (i < targets)
                                        {
                                            stari = TStar[i];
                                            wsclosest[1] = Distance(ship.X, ship.Y, stari.X, stari.Y);
                                            if ((wsclosest[1] < wsclosest[0]) & (_LastStarOwner[stari.Name] == -1))
                                            {
                                                wstarget[0] = stari;
                                                wsclosest[0] = wsclosest[1];
                                            }
                                            i = i + 1;
                                        }
                                        if (wstarget[0] == null)
                                        {
                                            PrintToDebug("WS2 " + ship.Code + " has changed to task 1", EnD);
                                            _shipTask[ship.Code] = 1;
                                            //SendMessage(ChatChannel.All, "WarShip " + ship.Code + " has switched to task 1");
                                        }
                                        else
                                        {
                                            _shipTargetOrder[ship.Code] = wstarget[0];
                                            if (wstarget[0] != null)
                                            {
                                                whobject = WormHoleWayFaster(ship, wstarget[0].X, wstarget[0].Y);
                                                if (whobject != null)
                                                {
                                                    if (wormholeusage[whobject] <= wmuselimit)
                                                    {
                                                        wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                        Move(ship, whobject.X, whobject.Y);
                                                    }
                                                    else
                                                    {
                                                        Move(ship, wstarget[0].X, wstarget[0].Y);
                                                    }
                                                }
                                                else
                                                {
                                                    Move(ship, wstarget[0].X, wstarget[0].Y);
                                                }
                                            }
                                            //SendMessage(ChatChannel.All, "WarShip " + ship.Code + " is searching " + wstarget[0].Name);
                                        }
                                        if (wstarget[0] != null)
                                        {
                                            PrintToDebug("WS2 " + ship.Code + " searching starsystem " + wstarget[0].Name, EnD);
                                        }
                                    }
                                    else if ((_shipTargetOrder[ship.Code] != null) & (_shipTask[ship.Code] == 2))
                                    {
                                        stari = _shipTargetOrder[ship.Code];
                                        //SendMessage(ChatChannel.All, "WarShip " + ship.Code + " is already searching " + stari.Name);
                                        if (stari != null)
                                        {
                                            whobject = WormHoleWayFaster(ship, stari.X, stari.Y);
                                            if (whobject != null)
                                            {
                                                if (wormholeusage[whobject] <= wmuselimit)
                                                {
                                                    wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                    Move(ship, whobject.X, whobject.Y);
                                                }
                                                else
                                                {
                                                    Move(ship, stari.X, stari.Y);
                                                }
                                            }
                                            else
                                            {
                                                Move(ship, stari.X, stari.Y);
                                            }
                                            PrintToDebug("WS2 " + ship.Code + " already searching starsystem " + stari.Name, EnD);
                                        }
                                    }
                                    #endregion
                                }
                                else if (_shipTask[ship.Code] == 3)
                                {
                                    #region Defense Warship Code
                                    PrintToDebug("WS3 " + ship.Code, EnD);
                                    //Defending warships will defend attacked starsystems rather than defend the border starsystems
                                    stari = null;
                                    intbuffer = 0;
                                    i = 0;
                                    while (i < mystars)
                                    {
                                        if (mystar[i] != null)
                                        {
                                            if ((_GetStarAttacks[mystar[i].Name] > intbuffer) & (_TDefenders[mystar[i].Name] < _GetStarAttacks[mystar[i].Name]))
                                            {
                                                intbuffer = _GetStarAttacks[mystar[i].Name];
                                                stari = mystar[i];
                                            }
                                        }
                                        i++;
                                    }
                                    if (stari == null)
                                    {
                                        stari = ClosestStarSystem(ship.X, ship.Y, 32767, FindSystemFlags.Unfriendly);
                                    }

                                    PrintToDebug("WS3 " + ship.Code + " processing defend", EnD);

                                    if (stari != null)
                                    {
                                        if (_TDefenders[stari.Name] < _GetStarAttacks[stari.Name])
                                        {
                                            _TDefenders[stari.Name] = _TDefenders[stari.Name] + 1;
                                            if (CapAlert >= 1) stari = mycap;
                                            whobject = WormHoleWayFaster(ship, stari.X, stari.Y);
                                            if (whobject != null)
                                            {
                                                if (wormholeusage[whobject] <= wmuselimit)
                                                {
                                                    wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                    Move(ship, whobject.X, whobject.Y);
                                                }
                                                else
                                                {
                                                    Defend(ship, stari);
                                                }
                                            }
                                            else
                                            {
                                                Defend(ship, stari);
                                            }
                                            PrintToDebug("WS3 " + ship.Code + " defending starsystem " + stari.Name, EnD);
                                            stari = ClosestStarSystem(ship.X, ship.Y, 5, FindSystemFlags.Unfriendly);
                                            if (stari != null)
                                            {
                                                if ((ship.X - 1 <= stari.X) & (ship.Y - 1 <= stari.Y) & (ship.X + 1 >= stari.X) & (ship.Y + 1 >= stari.Y))
                                                    AttackAdjacent(ship, false);
                                                else
                                                    AttackAdjacent(ship, true);
                                                Target(ship, stari);
                                            }
                                        }
                                        else
                                        {
                                            if (CapAlert >= 1)
                                            {
                                                stari = mycap;
                                                whobject = WormHoleWayFaster(ship, stari.X, stari.Y);
                                                if (whobject != null)
                                                {
                                                    if (wormholeusage[whobject] <= wmuselimit)
                                                    {
                                                        wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                        Move(ship, whobject.X, whobject.Y);
                                                    }
                                                    else
                                                    {
                                                        Defend(ship, stari);
                                                    }
                                                }
                                                else
                                                {
                                                    Defend(ship, stari);
                                                }
                                                stari = ClosestStarSystem(ship.X, ship.Y, 5, FindSystemFlags.Unfriendly);
                                                if (stari != null)
                                                {
                                                    if ((ship.X - 1 <= stari.X) & (ship.Y - 1 <= stari.Y) & (ship.X + 1 >= stari.X) & (ship.Y + 1 >= stari.Y))
                                                        AttackAdjacent(ship, false);
                                                    else
                                                        AttackAdjacent(ship, true);
                                                    Target(ship, stari);
                                                }
                                            }
                                            else
                                            {
                                                stari = ClosestStarSystem(ship.X, ship.Y, 32767, FindSystemFlags.Unfriendly);
                                                whobject = WormHoleWayFaster(ship, stari.X, stari.Y);
                                                if (whobject != null)
                                                {
                                                    if (wormholeusage[whobject] <= wmuselimit)
                                                    {
                                                        wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                        Move(ship, whobject.X, whobject.Y);
                                                    }
                                                    else
                                                    {
                                                        Target(ship, stari);
                                                    }
                                                }
                                                else
                                                {
                                                    Target(ship, stari);
                                                }
                                            }
                                            PrintToDebug("WS3 " + ship.Code + " defend overkill", EnD);
                                        }
                                    }
                                    //battleststions pose a big threat to Stratego 4s drone defenses so allow the warships to attack a nearby one.
                                    StarShipInfo battlese = null;
                                    battlese = ClosestStarShip(ship.X, ship.Y, 20, FindShipFlags.Enemy, ShipKnownFlags.Known);
                                    if (battlese != null)
                                        if (battlese.ShipType == StarShipType.BattleStation)
                                            Target(ship, battlese);
                                    #endregion
                                }
                                else if (_shipTask[ship.Code] == 4)
                                {
                                    #region Special Offensive Target Code
                                    PrintToDebug("WS4 " + ship.Code, EnD);
                                    //Cavalry warships
                                    if ((SE == false) | ((CapAlert == 2) & (CalAttack == false)))
                                    {
                                        stari = ClosestStarSystem(ship.X, ship.Y, 5, FindSystemFlags.Unfriendly);
                                        if (stari != null)
                                        {
                                            PrintToDebug("WS4 " + ship.Code + " attacking nearby enemy star.", EnD);
                                            if ((ship.X - 1 <= stari.X) & (ship.Y - 1 <= stari.Y) & (ship.X + 1 >= stari.X) & (ship.Y + 1 >= stari.Y))
                                                AttackAdjacent(ship, false);
                                            else
                                                AttackAdjacent(ship, true);
                                            Target(ship, stari);
                                        }
                                        else
                                        {
                                            PrintToDebug("WS4 " + ship.Code + " standing by.", EnD);
                                            meleewarships = meleewarships + 1;
                                            ad = (meleewarships / 2) + 1;
                                            if (ad < 1) ad = 1;
                                            if (CapAlert == 2)
                                                Defend(ship, mycap);
                                            else
                                                Move(ship, mycapx + Random(0 - ad, ad), mycapy + Random(0 - ad, ad));
                                        }
                                    }
                                    else
                                    {
                                        if ((CapitalTask == 1) & (ParentScanship != null))
                                        {
                                            //Stalemate breaker code
                                            if (CalAttack == true)
                                            {
                                                ad2 = DistanceQuick(ship.X, ship.Y, ParentScanship.X, ParentScanship.Y);
                                                if ((scanshipattack == true) | (ad2 >= 40))
                                                {
                                                    Target(ship, Ecap);
                                                    PrintToDebug("WS4 " + ship.Code + " attacking enemy capital.", EnD);
                                                }
                                                else
                                                {
                                                    if (ad2 <= 15)
                                                        Move(ship, SpyOrderX, SpyOrderY);
                                                    else
                                                        Move(ship, ParentScanship.X, ParentScanship.Y);
                                                }
                                            }
                                            else
                                            {
                                                stari = ClosestStarSystem(ship.X, ship.Y, 5, FindSystemFlags.Unfriendly);
                                                PrintToDebug("WS4 " + ship.Code + " getting ready.", EnD);
                                                ad = 2;
                                                ad1 = 9;
                                                while (ad1 < CavalryWarships)
                                                {
                                                    ad = ad + 1;
                                                    ad1 = (ad + 2) * (ad + 2);
                                                }
                                                if (mycapx < Ecapx) ad2 = mycapx + ad;
                                                else ad2 = mycapx - ad;
                                                if (mycapy < Ecapy) ad3 = mycapy + ad;
                                                else ad3 = mycapy - ad;
                                                if (DangerObjectWithinArea(ad2 - ad, ad3 - ad, ad, ad) == false)
                                                    Move(ship, ad2, ad3);
                                                else if (stari == null)
                                                {
                                                    Move(ship, mycapx + Random(0 - ad, ad), mycapy + Random(0 - ad, ad));
                                                }
                                                else
                                                {
                                                    if ((ship.X - 1 <= stari.X) & (ship.Y - 1 <= stari.Y) & (ship.X + 1 >= stari.X) & (ship.Y + 1 >= stari.Y))
                                                        AttackAdjacent(ship, false);
                                                    else
                                                        AttackAdjacent(ship, true);
                                                    Target(ship, stari);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //Normal code
                                            if (CalAttack == true)
                                            {
                                                whobject = WormHoleWayFaster(ship, Ecapx, Ecapy);
                                                if (whobject != null)
                                                {
                                                    if (wormholeusage[whobject] <= wmuselimit)
                                                    {
                                                        wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                        Move(ship, whobject.X, whobject.Y);
                                                    }
                                                    else
                                                    {
                                                        Target(ship, Ecap);
                                                    }
                                                }
                                                else
                                                {
                                                    Target(ship, Ecap);
                                                }
                                                if ((ship.X - 1 <= Ecapx) & (ship.Y - 1 <= Ecapy) & (ship.X + 1 >= Ecapx) & (ship.Y + 1 >= Ecapy))
                                                    AttackAdjacent(ship, false);
                                                else
                                                    AttackAdjacent(ship, true);
                                                PrintToDebug("WS4 " + ship.Code + " attacking enemy capital.", EnD);
                                            }
                                            else
                                            {
                                                stari = ClosestStarSystem(ship.X, ship.Y, 5, FindSystemFlags.Unfriendly);
                                                ad = 2;
                                                ad1 = 9;
                                                while (ad1 < CavalryWarships)
                                                {
                                                    ad = ad + 1;
                                                    ad1 = (ad + 2) * (ad + 2);
                                                }
                                                if (mycapx < Ecapx) ad2 = mycapx + ad;
                                                else ad2 = mycapx - ad;
                                                if (mycapy < Ecapy) ad3 = mycapy + ad;
                                                else ad3 = mycapy - ad;
                                                if (DangerObjectWithinArea(ad2 - ad, ad3 - ad, ad, ad) == false)
                                                    Move(ship, ad2, ad3);
                                                else if (stari == null)
                                                {
                                                    Move(ship, mycapx + Random(0 - ad, ad), mycapy + Random(0 - ad, ad));
                                                }
                                                else
                                                {
                                                    if ((ship.X - 1 <= stari.X) & (ship.Y - 1 <= stari.Y) & (ship.X + 1 >= stari.X) & (ship.Y + 1 >= stari.Y))
                                                        AttackAdjacent(ship, false);
                                                    else
                                                        AttackAdjacent(ship, true);
                                                    Target(ship, stari);
                                                }
                                                
                                                PrintToDebug("WS4 " + ship.Code + " getting ready.", EnD);
                                            }
                                        }
                                    }
                                    #endregion
                                }
                                //place addiotinal tasks here.
                                #endregion
                            }
                            if ((ship.ShipType == StarShipType.Drone) | (ship.ShipType == StarShipType.EMine) |
                                (ship.ShipType == StarShipType.HijackShip) | (ship.ShipType == StarShipType.InkSpot))
                            {
                                #region Drone Target Code
                                //PrintToDebug("DRO " + ship.Code, EnD);
                                if ((ship.ShipType == StarShipType.Drone) | (ship.ShipType == StarShipType.HijackShip))
                                    AttackAdjacent(ship, true);
                                shipi = ClosestStarShip(ship.X, ship.Y, 20, FindShipFlags.Enemy, ShipKnownFlags.Either);
                                if (shipi != null)
                                {
                                    if ((ship.Engines > wareng1 - 1) & (ship.Engines >= 9))
                                    {
                                        if (((shipi.X >= ship.X - (ship.Engines * ship.Engines / 16)) & (shipi.Y >= ship.Y - (ship.Engines * ship.Engines / 16)) & (shipi.X <= ship.X + (ship.Engines * ship.Engines / 16)) & (shipi.Y <= ship.Y + (ship.Engines * ship.Engines / 16))) == false)
                                            shipi = null;
                                    }
                                    else
                                    {
                                        if (((shipi.X >= ship.X - 10) & (shipi.Y >= ship.Y - 10) & (shipi.X <= ship.X + 10) & (shipi.Y <= ship.Y + 10)) == false)
                                            shipi = null;
                                    }
                                }
                                if (((ship.Engines > wareng1 - 1) & (ship.Engines >= 9)) | (ship.ShipType == StarShipType.EMine))
                                    stari = mycap;
                                else
                                    stari = ClosestStarSystem(ship.X, ship.Y, 32767, FindSystemFlags.Unfriendly);

                                //PrintToDebug("DRO " + ship.Code + " processing", EnD);
                                if (shipi != null)
                                {
                                    drattackstarship = false;
                                    for (int d = 0; d < LargeEnemies; d++)
                                        if (_LargeEnemy[d] == shipi)
                                            drattackstarship = true;
                                    if (drattackstarship == false)
                                        Move(ship, shipi.X, shipi.Y);
                                    else
                                        Target(ship, shipi);
                                }
                                else
                                {
                                    if ((CDAlert == true) & (ship.ShipType == StarShipType.InkSpot) & (ship.Engines > (wareng1 - 1)))
                                    {
                                        PrintToDebug("DRO " + ship.Code + " Cloak Alert", EnD);
                                        shipi = null;
                                        intClosest = 32767;
                                        i = 0;
                                        while (i < CDs)
                                        {
                                            intDSDist = DistanceQuick(CloakDet[i].X, CloakDet[i].Y, ship.X, ship.Y);
                                            if (intDSDist < intClosest)
                                            {
                                                intClosest = intDSDist;
                                                shipi = CloakDet[i];
                                            }
                                            i++;
                                        }
                                        if (shipi != null)
                                        {
                                            //patrol the area where the cloaked starships are
                                            //multiple cloak detectors can really narrow down the search area.
                                            if (shipi.CloakArrows.Contains(0) == true)
                                                Move(ship, Random(shipi.X - (shipi.Value / 2), shipi.X + (shipi.Value / 2)), Random(shipi.Y - shipi.Value, shipi.Y));
                                            if (shipi.CloakArrows.Contains(1) == true)
                                                Move(ship, Random(shipi.X, shipi.X + shipi.Value), Random(shipi.Y - shipi.Value, shipi.Y));
                                            if (shipi.CloakArrows.Contains(2) == true)
                                                Move(ship, Random(shipi.X, shipi.X + shipi.Value), Random(shipi.Y - (shipi.Value / 2), shipi.Y + (shipi.Value / 2)));
                                            if (shipi.CloakArrows.Contains(3) == true)
                                                Move(ship, Random(shipi.X, shipi.X + shipi.Value), Random(shipi.Y, shipi.Y + shipi.Value));
                                            if (shipi.CloakArrows.Contains(4) == true)
                                                Move(ship, Random(shipi.X - (shipi.Value / 2), shipi.X + (shipi.Value / 2)), Random(shipi.Y, shipi.Y + shipi.Value));
                                            if (shipi.CloakArrows.Contains(5) == true)
                                                Move(ship, Random(shipi.X - shipi.Value, shipi.X), Random(shipi.Y, shipi.Y + shipi.Value));
                                            if (shipi.CloakArrows.Contains(6) == true)
                                                Move(ship, Random(shipi.X - shipi.Value, shipi.X), Random(shipi.Y - (shipi.Value / 2), shipi.Y + (shipi.Value / 2)));
                                            if (shipi.CloakArrows.Contains(7) == true)
                                                Move(ship, Random(shipi.X - shipi.Value, shipi.X), Random(shipi.Y - shipi.Value, shipi.Y));
                                        }
                                    }
                                    else
                                    {
                                        //PrintToDebug("DRO " + ship.Code + " target code", EnD);
                                        //go into wormhole if destination is not known
                                        whobject = ClosestWormhole(ship.X, ship.Y, 20, false);
                                        if (whobject != null)
                                        {
                                            if (wormholeusage[whobject] < 1)
                                            {
                                                wormholeusage[whobject]++;
                                                Move(ship, whobject.X, whobject.Y);
                                            }
                                            else
                                            {
                                                ad2 = GetStarSystemIndex(stari.Name);
                                                Melees[ad2] = Melees[ad2] + 1;
                                                ad1 = (Melees[ad2] / 2) + 1;
                                                if (ad1 < 1) ad1 = 1;
                                                if ((stari == mycap) & (Melees[ad2] >= (TM * 5) + 6))
                                                {
                                                    PrintToDebug("DRO " + ship.Code + " Patrolling", EnD);
                                                    Point pdr = new Point(-1, -1);
                                                    int pdrclose = 32767;
                                                    foreach (Point pds in _DronesToThis.Keys)
                                                    {
                                                        if (_EnemyIntensity[pds] / 20 >= 1)
                                                            if (Distance(pds.X, pds.Y, ship.X, ship.Y) <= pdrclose)
                                                                if (_DronesToThis[pds] < _EnemyIntensity[pds] / 20)
                                                                {
                                                                    pdrclose = DistanceQuick(pds.X, pds.Y, ship.X, ship.Y);
                                                                    pdr = pds;
                                                                }
                                                    }
                                                    if (pdr.X > -1 && pdr.Y > -1)
                                                    {
                                                        Move(ship, (int)pdr.X, (int)pdr.Y);
                                                    }
                                                    else
                                                    {
                                                        Move(ship, stari.X + Random(0 - ad1, ad1), stari.Y + Random(0 - ad1, ad1));
                                                    }
                                                }
                                                else
                                                {
                                                    if (stari == mycap && Melees[ad2] <= 4)
                                                    {
                                                        if (ship.X >= mycapx - 1 && ship.Y >= mycapy - 1 && ship.X <= mycapx + 1 && ship.Y <= mycapy + 1)
                                                            Move(ship, stari.X + Random(0 - (ad1 + 1), (ad1 + 1)), stari.Y + Random(0 - (ad1 + 1), (ad1 + 1)));
                                                        else if (ship.X >= mycapx - 2 && ship.Y >= mycapy - 2 && ship.X <= mycapx + 2 && ship.Y <= mycapy + 2)
                                                            Defend(ship, mycap);
                                                        else
                                                            Move(ship, stari.X + Random(0 - ad1, ad1), stari.Y + Random(0 - ad1, ad1));

                                                    }
                                                    else
                                                    {
                                                        Move(ship, stari.X + Random(0 - ad1, ad1), stari.Y + Random(0 - ad1, ad1));
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            ad2 = GetStarSystemIndex(stari.Name);
                                            Melees[ad2] = Melees[ad2] + 1;
                                            ad1 = (Melees[ad2] / 2) + 1;
                                            if (ad1 < 1) ad1 = 1;
                                            if ((stari == mycap) & (Melees[ad2] >= (TM * 5) + 6))
                                            {
                                                //PrintToDebug("DRO " + ship.Code + " Patrolling", EnD);
                                                Point pdr = new Point(-1, -1);
                                                int pdrclose = 32767;
                                                foreach (Point pds in _DronesToThis.Keys)
                                                {
                                                    if (_EnemyIntensity[pds] / 20 >= 1)
                                                        if (Distance(pds.X, pds.Y, ship.X, ship.Y) <= pdrclose)
                                                            if (_DronesToThis[pds] < _EnemyIntensity[pds] / 20)
                                                            {
                                                                pdrclose = DistanceQuick(pds.X, pds.Y, ship.X, ship.Y);
                                                                pdr = pds;
                                                            }
                                                }
                                                if (pdr.X > -1 && pdr.Y > -1)
                                                {
                                                    Move(ship, (int)pdr.X, (int)pdr.Y);
                                                }
                                                else
                                                {
                                                    Move(ship, stari.X + Random(0 - ad1, ad1), stari.Y + Random(0 - ad1, ad1));
                                                }
                                            }
                                            else
                                            {
                                                if (stari == mycap && Melees[ad2] <= 4)
                                                {
                                                    if (ship.X >= mycapx - 1 && ship.Y >= mycapy - 1 && ship.X <= mycapx + 1 && ship.Y <= mycapy + 1)
                                                        Move(ship, stari.X + Random(0 - (ad1 + 1), (ad1 + 1)), stari.Y + Random(0 - (ad1 + 1), (ad1 + 1)));
                                                    else if (ship.X >= mycapx - 2 && ship.Y >= mycapy - 2 && ship.X <= mycapx + 2 && ship.Y <= mycapy + 2)
                                                        Defend(ship, mycap);
                                                    else
                                                        Move(ship, stari.X + Random(0 - ad1, ad1), stari.Y + Random(0 - ad1, ad1));
                                                }
                                                else
                                                {
                                                    Move(ship, stari.X + Random(0 - ad1, ad1), stari.Y + Random(0 - ad1, ad1));
                                                }
                                            }
                                        }
                                    }
                                }
                                //PrintToDebug("DRO " + ship.Code + " end processing", EnD);
                                #endregion
                            }
                            if ((ship.ShipType == StarShipType.TechShip) | (ship.ShipType == StarShipType.RemoteViewer))
                            {
                                #region Techship Code
                                //Keep techships from going into known blackholes!
                                BlackHoleInfo bhtarget = null;
                                bool zonepoint = false;
                                Point zonept = new Point();
                                int tsdist1 = 20;
                                int tsdist2 = 20;
                                int bhdist = 20;
                                for (int bh = 0; bh < BlackHoles.Count; bh++)
                                {
                                    if (DistanceQuick(BlackHoles[bh].X, BlackHoles[bh].Y, ship.X, ship.Y) <= bhdist)
                                    {
                                        bhdist = DistanceQuick(BlackHoles[bh].X, BlackHoles[bh].Y, ship.X, ship.Y);
                                        bhtarget = BlackHoles[bh];
                                    }
                                }
                                foreach (Point enp in _EnemyIntensity.Keys)
                                {
                                    tsdist1 = DistanceQuick(enp.X, enp.Y, ship.X, ship.Y);
                                    if (tsdist1 < tsdist2)
                                    {
                                        tsdist2 = tsdist1;
                                        zonepoint = true;
                                        zonept.X = enp.X;
                                        zonept.Y = enp.Y;
                                    }
                                }
                                shipi = ClosestStarShip(ship.X, ship.Y, 20, FindShipFlags.Enemy, ShipKnownFlags.Either);
                                stari = ClosestStarSystem(ship.X, ship.Y, 32767, FindSystemFlags.Friendly);
                                if (bhtarget != null)
                                {
                                    destx = ship.X + ((ship.X - bhtarget.X) * 2);
                                    desty = ship.Y + ((ship.Y - bhtarget.Y) * 2);
                                }
                                else if (shipi != null)
                                {
                                    destx = ship.X + ((ship.X - shipi.X) * 2);
                                    desty = ship.Y + ((ship.Y - shipi.Y) * 2);
                                }
                                else if (zonepoint == true)
                                {
                                    destx = (int)(ship.X + ((ship.X - zonept.X) * 2));
                                    desty = (int)(ship.Y + ((ship.Y - zonept.Y) * 2));
                                }
                                else
                                {
                                    if (Clusterx > stari.X) ad1 = -20;
                                    else ad1 = 20;
                                    if (Clustery > stari.Y) ad2 = -20;
                                    else ad2 = 20;
                                    if (DistanceQuick(ship.X, ship.Y, stari.X, stari.Y) >= 20)
                                    {
                                        destx = (int)(ship.X + ((ship.X - stari.X) * 2));
                                        desty = (int)(ship.Y + ((ship.Y - stari.Y) * 2));
                                    }
                                    else
                                    {
                                        destx = stari.X + ad1;
                                        desty = stari.Y + ad2;
                                    }
                                }
                                Move(ship, destx, desty);

                                if (ship.ShipType == StarShipType.RemoteViewer)
                                {
                                    if (SE == true)
                                        SetRemoteViewPoint(ship, Ecapx, Ecapy);
                                }
                                #endregion
                            }
                            if (((ship.ShipType == StarShipType.StarTillery) | (ship.ShipType == StarShipType.ScanShip) |
                                (ship.ShipType == StarShipType.SpyShip) | (ship.ShipType == StarShipType.CommandShip) |
                                (ship.ShipType == StarShipType.BeamShip) | (ship.ShipType == StarShipType.ParalyShip) | 
                                (ship.ShipType == StarShipType.Director)) & (ship != ParentScanship))
                            {
                                #region Startillery Code and Bunker System Code
                                bool overridenebula = false;
                                PrintToDebug("STT " + ship.Code, EnD);
                                irange = 0;
                                if ((ship.ShipType == StarShipType.StarTillery) | (ship.ShipType == StarShipType.CommandShip) | (ship.ShipType == StarShipType.BeamShip))
                                    irange = ship.Value - (ship.Value / 8);
                                else
                                    irange = ship.Value - (ship.Value / 6);
                                if (irange < 5) irange = 5;
                                // Health is in Percentage  IsDamaged is in boolean
                                shiphealth = ship.Health;
                                shipdamaged = ship.IsDamaged;
                                basefriendlystar = true;
                                attackstarship = false;
                                engagethreshold = (TM * 4) + 15;
                                tarStar1 = ClosestStarSystem(ship.X, ship.Y, 32767, FindSystemFlags.Enemy);
                                if (tarStar1 == null) tarStar1 = ClosestStarSystem(ship.X, ship.Y, 32767, FindSystemFlags.Unfriendly);
                                tarShip1 = ClosestStarShip(ship.X, ship.Y, irange * 4, FindShipFlags.Enemy, ShipKnownFlags.Either);
                                //Determine which type of unit to defend against
                                if ((tarShip1 != null) & (ship.ShipType != StarShipType.CommandShip) & (ship.ShipType != StarShipType.Director))
                                {
                                    stargetx = tarStar1.X;
                                    stargety = tarStar1.Y;
                                    if (CapAlert == 1)
                                    {
                                        basefriendlystar = true;
                                    }
                                    else
                                    {
                                        stardist = Distance(ship.X, ship.Y, tarStar1.X, tarStar1.Y);
                                        shipdist = Distance(ship.X, ship.Y, tarShip1.X, tarShip1.Y);
                                        if (PlayerHasStartillery[tarShip1.OwnerInt] == true)
                                        {
                                            ENRange = MaxSTRange[tarShip1.OwnerInt];
                                            if (ENRange > ship.Value)
                                            {
                                                basefriendlystar = true;
                                                if ((ship.ShipType == StarShipType.StarTillery) | (ship.ShipType == StarShipType.CommandShip) | (ship.ShipType == StarShipType.BeamShip) | (ship.ShipType == StarShipType.ParalyShip))
                                                    irange = ship.Value;
                                                else
                                                    irange = ship.Value - (ship.Value / 8);
                                            }
                                            else
                                            {
                                                if ((ship.ShipType == StarShipType.StarTillery) | (ship.ShipType == StarShipType.CommandShip) | (ship.ShipType == StarShipType.BeamShip) | (ship.ShipType == StarShipType.ParalyShip))
                                                    irange = ship.Value - (ship.Value / 12);
                                                else
                                                    irange = ship.Value - (ship.Value / 6);
                                            }
                                            if (irange < 5) irange = 5;
                                        }
                                        if (((shipdist < stardist) | (tarStar1.OwnerInt == -1)) & (_EnShipsNearStar[tarStar1.Name] > 0))
                                            basefriendlystar = false;
                                        else
                                            basefriendlystar = true;

                                    }
                                }
                                else
                                {
                                    basefriendlystar = true;
                                }
                                escortstarship = false;
                                beamattackstarship = false;
                                beamattackobject = null;

                                PrintToDebug("STT " + ship.Code + " processing attack", EnD);
                                //exclusive beam ship attack code
                                if ((tarShip1 != null) & (ship.ShipType == StarShipType.BeamShip))
                                {
                                    //do not target a ship that another beamship has targeted;
                                    ad1 = -100;
                                    tarShip2 = null;
                                    for (int d = 0; d < EnemyShips; d++)
                                    {
                                        ad2 = Math.Abs(enemyship[d].X - ship.X);
                                        ad3 = Math.Abs(enemyship[d].Y - ship.Y);
                                        ad2 = ad2 * ad2;
                                        ad3 = ad3 * ad3;
                                        floArcdist = Math.Sqrt(ad2 + ad3);
                                        bmshipcancel = false;
                                        for (int e = 0; e < MSs; e++)
                                        {
                                            if ((_BeamShipTarget[sBeamShip[e].Code] == enemyship[d]) & (sBeamShip[e] != ship))
                                                bmshipcancel = true;
                                        }
                                        if ((floArcdist <= ship.Value) & (ad1 <= (enemyship[d].Value + 1) * (enemyship[d].Engines + 1)) & (bmshipcancel == false))
                                        {
                                            tarShip2 = enemyship[d];
                                            ad1 = (enemyship[d].Value + 1) * (enemyship[d].Engines + 1);
                                        }
                                    }
                                    if (tarShip2 != null)
                                    {
                                        _BeamShipTarget[ship.Code] = tarShip2;
                                        beamattackstarship = true;
                                        beamattackobject = tarShip2;
                                    }
                                }
                                //SendMessage(ChatChannel.All, "DebugST2");
                                if (basefriendlystar == false)
                                {
                                    //determine if the ranged starship can escort a starship or not.
                                    stargetx = tarShip1.X;
                                    stargety = tarShip1.Y;
                                    ad2 = Math.Abs(tarShip1.X - ship.X);
                                    ad3 = Math.Abs(tarShip1.Y - ship.Y);
                                    ad2 = ad2 * ad2;
                                    ad3 = ad3 * ad3;
                                    floArcdist = Math.Sqrt(ad2 + ad3);
                                    if ((floArcdist >= irange - 1) & (floArcdist <= ship.Value))
                                        escortstarship = true;
                                    if ((ship.ShipType == StarShipType.BeamShip) & (floArcdist <= ship.Value))
                                        beamattackstarship = true;
                                }
                                else
                                {
                                    //base to my capital if the star is not a threat.
                                    if ((tarStar1.Visible == true) & (tarStar1.OwnerInt == -1))
                                        tarStar1 = mycap;
                                    stargetx = tarStar1.X;
                                    stargety = tarStar1.Y;
                                }

                                PrintToDebug("STT " + ship.Code + " covered code", EnD);

                                //find closest star to defend that is covered by scanners and not on the edge of my cluster}
                                tarStar2 = null;
                                tarStar3 = null;
                                if ((ship.Cloaked == true) & (STs > engagethreshold) & (cloakedSSs > 0))
                                {
                                    intclosestst = 99999;
                                    intcloseststb = 99999;
                                    i = 0;
                                    while (i < targets)
                                    {
                                        if (CapAlert == 0)
                                        {
                                            stari = TStar[i];
                                            ad2 = TStar[i].X;
                                            ad3 = TStar[i].Y;
                                        }
                                        else
                                        {
                                            ad2 = mycapx;
                                            ad3 = mycapy;
                                            stari = mycap;
                                        }
                                        ad2 = Math.Abs(ad2 - stargetx);
                                        ad3 = Math.Abs(ad3 - stargety);
                                        if (ad2 > ad3) intDSDist = ad2;
                                        else intDSDist = ad3;
                                        ad2 = Math.Abs(ad2 - ship.X);
                                        ad3 = Math.Abs(ad3 - ship.Y);
                                        if (ad2 > ad3) intDSDistb = ad2;
                                        else intDSDistb = ad3;
                                        if (intDSDist <= intclosestst)
                                        {
                                            intclosestst = intDSDist;
                                            tarStar2 = stari;
                                        }
                                        if (intDSDistb <= intcloseststb)
                                        {
                                            intcloseststb = intDSDistb;
                                            tarStar3 = stari;
                                        }
                                        i = i + 1;
                                    }
                                }
                                else
                                {
                                    intclosestst = 99999;
                                    intcloseststb = 99999;
                                    i = 0;
                                    while (i < mystars)
                                    {
                                        if (CapAlert == 0)
                                            stari = mystar[i];
                                        else
                                            stari = mycap;
                                        intDSDist = DistanceQuick(stargetx, stargety, stari.X, stari.Y);
                                        intDSDistb = DistanceQuick(ship.X, ship.Y, stari.X, stari.Y);
                                        if ((intDSDist < intclosestst) & (_StarCovered[stari.Name] == true) & (_StarSecured[stari.Name] == true))
                                        {
                                            intclosestst = intDSDist;
                                            tarStar2 = stari;
                                        }
                                        if ((intDSDistb < intcloseststb) & (_StarCovered[stari.Name] == true) & (_StarSecured[stari.Name] == true))
                                        {
                                            intcloseststb = intDSDistb;
                                            tarStar3 = stari;
                                        }
                                        i = i + 1;
                                    }
                                }

                                PrintToDebug("STT " + ship.Code + " processing covered", EnD);

                                if (tarStar2 == null) tarStar2 = tarStar3;
                                if (tarStar2 == null) tarStar2 = ClosestStarSystem(tarStar1.X, tarStar1.Y, 32767, FindSystemFlags.Friendly);
                                if (tarStar2 != null)
                                {
                                        tarStar3 = ClosestStarSystem(tarStar2.X - 2, tarStar2.Y - 2, 32767, FindSystemFlags.Friendly);
                                        tarStar4 = ClosestStarSystem(tarStar2.X + 2, tarStar2.Y + 2, 32767, FindSystemFlags.Friendly);
                                        tarStar5 = ClosestStarSystem(tarStar2.X + 2, tarStar2.Y - 2, 32767, FindSystemFlags.Friendly);
                                        tarStar6 = ClosestStarSystem(tarStar2.X - 2, tarStar2.Y + 2, 32767, FindSystemFlags.Friendly);
                                        intDSDist = Convert.ToInt32(Distance(ship.X, ship.Y, tarStar2.X, tarStar2.Y));
                                }
                                else
                                {
                                    tarStar2 = tarStar1;
                                }
                                if ((intDSDist >= irange + 5) & (tarShip1 != null)) attackstarship = true;
                                if ((basefriendlystar == false) & (attackstarship == false))
                                {
                                    PrintToDebug("ST " + ship.Code + " DEFEND MODE", EnD);
                                    for (int d = 0; d < 8; d++) defendslope[d] = 0;
                                    ad1 = _EnShipsNearStar[tarStar2.Name];
                                    List<string> tmpstringlist = new List<string>();
                                    ConvertStarShipList(_EnShipList[tarStar2.Name], tmpstringlist);
                                    i = 0;
                                    while (i < ad1)
                                    {
                                        tmpstring = tmpstringlist[i];
                                        tarShip2 = FindStarShip(tmpstring);
                                        if (tarShip2 != null)
                                        {
                                            if ((tarShip2.X - tarStar2.X == 0) | (tarShip2.Y - tarStar2.Y == 0))
                                                tantar = 0;
                                            else
                                            {
                                                diffx = tarShip2.X - tarStar2.X;
                                                diffy = tarShip2.Y - tarStar2.Y;
                                                tantar = diffy / diffx;
                                            }
                                            direction = FindDirection8(tarShip2.X - tarStar2.X, tarShip2.Y - tarStar2.Y, tantar);
                                            defendslope[direction - 1] = defendslope[direction - 1] + 1;
                                        }
                                        i = i + 1;
                                    }
                                    ad1 = 0;
                                    ad2 = -1;
                                    tmpstring = "";
                                    for (int d = 0; d < 8; d++)
                                    {
                                        tmpstring = tmpstring + defendslope[d].ToString() + ",";
                                        if (defendslope[d] > ad1)
                                        {
                                            ad2 = d;
                                            ad1 = defendslope[d];
                                        }
                                    }
                                    if (ship.Cloaked == true)
                                        ad3 = (irange / 3) + (ad1 / 8) + 1;
                                    else
                                        ad3 = (irange / 3) + (ad1 / 16) + 1;
                                    if (ad2 == -1)
                                    {
                                        orderx = ship.X;
                                        ordery = ship.Y;
                                    }
                                    if (ad2 == 0)
                                    {
                                        orderx = tarStar2.X;
                                        ordery = tarStar2.Y + ad3;
                                    }
                                    if (ad2 == 1)
                                    {
                                        orderx = tarStar2.X - ad3;
                                        ordery = tarStar2.Y + ad3;
                                    }
                                    if (ad2 == 2)
                                    {
                                        orderx = tarStar2.X - ad3;
                                        ordery = tarStar2.Y;
                                    }
                                    if (ad2 == 3)
                                    {
                                        orderx = tarStar2.X - ad3;
                                        ordery = tarStar2.Y - ad3;
                                    }
                                    if (ad2 == 4)
                                    {
                                        orderx = tarStar2.X;
                                        ordery = tarStar2.Y - ad3;
                                    }
                                    if (ad2 == 5)
                                    {
                                        orderx = tarStar2.X + ad3;
                                        ordery = tarStar2.Y - ad3;
                                    }
                                    if (ad2 == 6)
                                    {
                                        orderx = tarStar2.X + ad3;
                                        ordery = tarStar2.Y;
                                    }
                                    if (ad2 == 7)
                                    {
                                        orderx = tarStar2.X + ad3;
                                        ordery = tarStar2.Y + ad3;
                                    }
                                }
                                else if ((basefriendlystar == true) & (attackstarship == false))
                                {
                                    PrintToDebug("ST " + ship.Code + " BASE MODE", EnD);
                                    star3a = null;
                                    star3b = null;
                                    intclosestst = 32767;
                                    intcloseststb = 32767;
                                    i = 0;
                                    while (i < targets)
                                    {
                                        ad2 = TStar[i].X;
                                        ad3 = TStar[i].Y;
                                        ad2 = Math.Abs(ad2 - tarStar2.X);
                                        ad3 = Math.Abs(ad3 - tarStar2.Y);
                                        if (ad2 > ad3) intDSDist = ad2;
                                        else intDSDist = ad3;
                                        if (TStar[i] != tarStar2)
                                        {
                                            if ((intDSDist < intclosestst) & (_LastStarOwner[TStar[i].Name] == 1) & (TStar[i].Visible == false))
                                            {
                                                intclosestst = intDSDist;
                                                star3a = TStar[i];
                                            }
                                            if ((intDSDist < intcloseststb) & (TStar[i].Visible == false))
                                            {
                                                intcloseststb = intDSDist;
                                                star3b = TStar[i];
                                            }
                                        }
                                        i = i + 1;
                                    }
                                    if (star3a == null) star3a = star3b;
                                    if (star3a == null) star3a = ClosestStarSystem(tarStar2.X, tarStar2.Y, 32767, FindSystemFlags.Unfriendly);
                                    if (ship.Cloaked == true)
                                    {
                                        if (star3a.X < tarStar2.X) orderx = tarStar2.X + ((irange / 3) + 2);
                                        else if (star3a.X == tarStar2.X) orderx = tarStar2.X;
                                        else orderx = tarStar2.X - ((irange / 3) + 2);
                                        if (star3a.Y < tarStar2.Y) ordery = tarStar2.Y + ((irange / 3) + 2);
                                        else if (star3a.Y == tarStar2.Y) ordery = tarStar2.Y;
                                        else ordery = tarStar2.Y - ((irange / 3) + 2);
                                    }
                                    else
                                    {
                                        if (tarStar2 == mycap) irange = 4;
                                        if (star3a.X < tarStar2.X) orderx = tarStar2.X + ((irange / 4) + 1);
                                        else if (star3a.X == tarStar2.X) orderx = tarStar2.X;
                                        else orderx = tarStar2.X - ((irange / 4) + 1);
                                        if (star3a.Y < tarStar2.Y) ordery = tarStar2.Y + ((irange / 4) + 1);
                                        else if (star3a.Y == tarStar2.Y) ordery = tarStar2.Y;
                                        else ordery = tarStar2.Y - ((irange / 4) + 1);
                                    }
                                }
                                else if ((attackstarship == true) & (tarShip1 != null))
                                {
                                    PrintToDebug("ST " + ship.Code + " ATTACK MODE", EnD);
                                    //Attack starships in the way
                                    stargetx = tarShip1.X;
                                    stargety = tarShip1.Y;
                                    ad2 = Math.Abs(stargetx - ship.X);
                                    ad3 = Math.Abs(stargety - ship.Y);
                                    ad2 = ad2 * ad2;
                                    ad3 = ad3 * ad3;
                                    floArcdist = Math.Sqrt(ad2 + ad3);
                                    if (irange < 5) irange = 5;
                                    diffx = Convert.ToDouble(ship.X - stargetx) / (floArcdist / Convert.ToDouble(irange));
                                    diffy = Convert.ToDouble(ship.Y - stargety) / (floArcdist / Convert.ToDouble(irange));
                                    orderx = stargetx + Convert.ToInt32(diffx);
                                    ordery = stargety + Convert.ToInt32(diffy);
                                    attcancel = false;
                                    //check the calculated position for any enemy objects.}
                                    for (int d = 0; d < 2; d++)
                                    {
                                        if (d == 0) star3a = ClosestStarSystem(ship.X, ship.Y, 8, FindSystemFlags.Unfriendly);
                                        if (d == 1) star3a = ClosestStarSystem(orderx, ordery, 8, FindSystemFlags.Unfriendly);
                                        if (star3a != null)
                                        {
                                            if ((_LastStarOwner[star3a.Name] != 0) | (star3a.Visible == false))
                                            {
                                                ad2 = Math.Abs(star3a.X - ship.X);
                                                ad3 = Math.Abs(star3a.Y - ship.Y);
                                                if (ad2 > ad3) intDSDist = ad2;
                                                else intDSDist = ad3;
                                                if (intDSDist <= 4) attcancel = true;
                                            }
                                        }
                                    }
                                    for (int d = 0; d < 2; d++)
                                    {
                                        if (d == 0) shipi = ClosestStarShip(ship.X, ship.Y, 6, FindShipFlags.Enemy, ShipKnownFlags.Either);
                                        if (d == 1) shipi = ClosestStarShip(orderx, ordery, 6, FindShipFlags.Enemy, ShipKnownFlags.Either);
                                        if (shipi != null)
                                        {
                                            ad2 = Math.Abs(shipi.X - ship.X);
                                            ad3 = Math.Abs(shipi.Y - ship.Y);
                                            if (ad2 > ad3) intDSDist = ad2;
                                            else intDSDist = ad3;
                                            if (intDSDist <= 3) attcancel = true;
                                        }
                                    }
                                    if (attcancel == true)
                                    {
                                        orderx = mycapx;
                                        ordery = mycapy;
                                    }
                                }

                                PrintToDebug("STT " + ship.Code + " order attack", EnD);
                                //order the startillery
                                if (beamattackstarship == false)
                                {
                                    if (escortstarship == false)
                                    {
                                        whobject = WormHoleWayFaster(ship, orderx, ordery);
                                        if (whobject != null)
                                        {
                                            if (wormholeusage[whobject] <= wmuselimit)
                                            {
                                                wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                Move(ship, whobject.X, whobject.Y);
                                                overridenebula = true;
                                            }
                                            else
                                            {
                                                Move(ship, orderx, ordery);
                                            }
                                        }
                                        else
                                        {
                                            Move(ship, orderx, ordery);
                                        }
                                    }
                                    else if (tarShip1 != null)
                                    {
                                        Escort(ship, tarShip1, ship.X - tarShip1.X, ship.Y - tarShip1.Y);
                                    }
                                }
                                else if (beamattackobject != null)
                                {
                                    Target(ship, beamattackobject);
                                }

                                PrintToDebug("STT " + ship.Code + " bunker processing", EnD);
                                if (Distance(ship.X, ship.Y, tarStar2.X, tarStar2.Y) <= ship.Value + (ship.Engines / 4))
                                {
                                    if (((_MyBorderScan[tarStar2.Name] == true) | (_EnShipsNearStar[tarStar2.Name] > 2)) & (tarStar2 != mycap))
                                    {
                                        if ((_StarCovered[tarStar2.Name] == true) & (tarStar2.Scanners <= ship.Value + 1)) BuildScanners(tarStar2, 5);
                                        //NEW IMPROVED BUNKER SYSTEM
                                        if (meleedrones <= targets * 20)
                                        {
                                            if (tarStar2.Resources <= ShipCostCalculator.GetCost(StarShipType.StarTillery, 20, TRange, cloaker, null) / 1.2)
                                            {
                                                SetAutoStarShipType(tarStar2, StarShipType.Drone, wareng0, 0, cloaker);
                                                SetAutoStarShip(tarStar2, true);
                                            }
                                            if ((tarStar3 != tarStar2) & (tarStar3 != mycap) & ((stargetx < tarStar2.X) | (stargety < tarStar2.Y)))
                                                if (tarStar3.Resources <= ShipCostCalculator.GetCost(StarShipType.StarTillery, 20, TRange, cloaker, null) / 1.2)
                                                {
                                                    SetAutoStarShipType(tarStar3, StarShipType.Drone, wareng0, 0, cloaker);
                                                    SetAutoStarShip(tarStar3, true);
                                                }
                                            if ((tarStar4 != tarStar2) & (tarStar4 != mycap) & ((stargetx > tarStar2.X) | (stargety > tarStar2.Y)))
                                                if (tarStar4.Resources <= ShipCostCalculator.GetCost(StarShipType.StarTillery, 20, TRange, cloaker, null) / 1.2)
                                                {
                                                    SetAutoStarShipType(tarStar4, StarShipType.Drone, wareng0, 0, cloaker);
                                                    SetAutoStarShip(tarStar4, true);
                                                }
                                            if ((tarStar5 != tarStar2) & (tarStar5 != mycap) & ((stargetx > tarStar2.X) | (stargety < tarStar2.Y)))
                                                if (tarStar5.Resources <= ShipCostCalculator.GetCost(StarShipType.StarTillery, 20, TRange, cloaker, null) / 1.2)
                                                {
                                                    SetAutoStarShipType(tarStar5, StarShipType.Drone, wareng0, 0, cloaker);
                                                    SetAutoStarShip(tarStar5, true);
                                                }
                                            if ((tarStar6 != tarStar2) & (tarStar6 != mycap) & ((stargetx < tarStar2.X) | (stargety > tarStar2.Y)))
                                                if (tarStar6.Resources <= ShipCostCalculator.GetCost(StarShipType.StarTillery, 20, TRange, cloaker, null) / 1.2)
                                                {
                                                    SetAutoStarShipType(tarStar6, StarShipType.Drone, wareng0, 0, cloaker);
                                                    SetAutoStarShip(tarStar6, true);
                                                }
                                        }
                                    }
                                    else if ((tarStar2 != mycap) & (_EnShipsNearStar[tarStar2.Name] > 0))
                                    {
                                        if (meleedrones <= targets * 20)
                                        {
                                            if (tarStar2.Resources <= ShipCostCalculator.GetCost(StarShipType.StarTillery, 20, TRange, cloaker, null) / 1.2)
                                            {
                                                SetAutoStarShipType(tarStar2, StarShipType.Drone, wareng0, 0, cloaker);
                                                SetAutoStarShip(tarStar2, true);
                                            }
                                        }
                                        if ((_StarCovered[tarStar2.Name] == true) & (tarStar2.Scanners <= ship.Value + 1)) BuildScanners(tarStar2, 5);
                                    }
                                }

                                PrintToDebug("STT " + ship.Code + " alert and repair.", EnD);

                                //Alert and repair functions!
                                shipi = null;
                                if (ship.Health < 100) damagedstarships++;
                                if ((ship.Health < 100) & (BSs > 0))
                                {
                                    //find closest battlestation to go to for repair if available.
                                    intClosest = 32767;
                                    for (int d = 0; d < BSs; d++)
                                    {
                                        if (_BattleStationSlots[BS[d].Code] < 8)
                                        {
                                            intDSDist = DistanceQuick(ship.X, ship.Y, BS[d].X, BS[d].Y);
                                            if (intDSDist < intClosest)
                                            {
                                                shipi = BS[d];
                                                intClosest = intDSDist;
                                            }
                                        }
                                    }
                                }
                                tarShip1 = ClosestStarShip(ship.X, ship.Y, (int)(irange * 1.5), FindShipFlags.Enemy, ShipKnownFlags.Either);
                                if (shipi != null)
                                {
                                    PrintToDebug("STT " + ship.Code + " heading to a battlestation", EnD);
                                    _BattleStationSlots[shipi.Code] = _BattleStationSlots[shipi.Code] + 1;
                                    if ((ship.X >= shipi.X - 1) & (ship.Y >= shipi.Y - 1) & (ship.X <= shipi.X + 1) & (ship.Y <= shipi.Y + 1))
                                        ClearOrder(ship);
                                    else
                                        Move(ship, shipi.X, shipi.Y);
                                    overridenebula = true;
                                }
                                else if ((((shiphealth <= 89) & (tarShip1 != null)) | ((shiphealth < 100) & (tarShip1 == null))) & (RSs > 0))
                                {
                                    PrintToDebug("STT " + ship.Code + " heading to a repairship", EnD);
                                    if ((ship.X >= mycapx - 5) & (ship.Y >= mycapy - 5) & (ship.X <= mycapx + 5) & (ship.Y <= mycapy + 5))
                                    {
                                        ClearOrder(ship);
                                    }
                                    else
                                    {
                                        whobject = WormHoleWayFaster(ship, mycapx, mycapy);
                                        if (whobject != null)
                                        {
                                            if (wormholeusage[whobject] <= wmuselimit)
                                            {
                                                wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                Move(ship, whobject.X, whobject.Y);
                                                overridenebula = true;
                                            }
                                            else
                                            {
                                                Move(ship, mycapx, mycapy);
                                            }
                                        }
                                        else
                                        {
                                            Move(ship, mycapx, mycapy);
                                        }
                                    }
                                    overridenebula = true;
                                }
                                else if ((((shiphealth < 90) & (tarShip1 != null)) | ((shiphealth < 100) & (tarShip1 == null))) & (usepulsarrepair == true))
                                {
                                    PrintToDebug("STT " + ship.Code + " heading to a pulsar", EnD);
                                    pultarget = ClosestSecuredPulsar(ship.X,ship.Y,(ship.Value + 5) * (int)(400 / ship.Health),_PulsarSecured);
                                    if (pultarget != null)
                                    {
                                        whobject = WormHoleWayFaster(ship, pultarget.X, pultarget.Y);
                                        if (whobject != null)
                                        {
                                            if (wormholeusage[whobject] <= wmuselimit)
                                            {
                                                wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                Move(ship, whobject.X, whobject.Y);
                                            }
                                            else
                                            {
                                                Move(ship, pultarget.X, pultarget.Y);
                                            }
                                        }
                                        else
                                        {
                                            Move(ship, pultarget.X, pultarget.Y);
                                        }
                                    }
                                    overridenebula = true;
                                }

                                PrintToDebug("STT " + ship.Code + " captial alert", EnD);

                                if (CapAlert == 1 && STs >= 5)
                                {
                                    intDSDist = DistanceQuick(ship.X, ship.Y, mycapx, mycapy);
                                    if (intDSDist < (MinSTDist * 1.5))
                                    {
                                        whobject = WormHoleWayFaster(ship, mycapx, mycapy);
                                        if (whobject != null)
                                        {
                                            if (wormholeusage[whobject] <= wmuselimit)
                                            {
                                                wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                Move(ship, whobject.X, whobject.Y);
                                                overridenebula = true;
                                            }
                                            else
                                            {
                                                Move(ship, mycapx, mycapy);
                                            }
                                        }
                                        else
                                        {
                                            Move(ship, mycapx, mycapy);
                                        }
                                    }
                                }
                                if (CapAlert == 2)
                                {
                                    intRange = 1;
                                    if (MycapShip.IdentifiedByMe == true)
                                        intRange = (ship.Engines / MycapShip.Engines);
                                    if (intRange <= 0) intRange = 1;
                                    //don't move to capital if too far away to get there in time.
                                    if ((DistanceQuick(ship.X, ship.Y, mycapx, mycapy) / intRange) - irange <= DistanceQuick(mycapx, mycapy, MycapShip.X, MycapShip.Y))
                                    {
                                        if (MycapShip.X < mycapx) orderx = mycapx + (irange / 3);
                                        else if (MycapShip.Y == mycapx) orderx = mycapx;
                                        else orderx = mycapx - (irange / 3);
                                        if (MycapShip.Y < mycapy) ordery = mycapy + (irange / 3);
                                        else if (MycapShip.Y == mycapy) ordery = mycapy;
                                        else ordery = mycapy - (irange / 3);
                                        whobject = WormHoleWayFaster(ship, orderx, ordery);
                                        if (whobject != null)
                                        {
                                            if (wormholeusage[whobject] <= wmuselimit)
                                            {
                                                wormholeusage[whobject] = wormholeusage[whobject] + 1;
                                                Move(ship, whobject.X, whobject.Y);
                                            }
                                            else
                                            {
                                                Move(ship, orderx, ordery);
                                            }
                                        }
                                        else
                                        {
                                            Move(ship, orderx, ordery);
                                        }
                                    }
                                }

                                //special processing for scanship and spyship
                                if (((ship.ShipType == StarShipType.ScanShip) | (ship.ShipType == StarShipType.SpyShip)) & (overridenebula == false))
                                {
                                    //see if the order will get into nebula
                                    if (GetTerrain(orderx, ordery) == TerrainType.Nebula)
                                    {
                                        //find any nearby clearing to see out of
                                        bool targfound = false;
                                        Point neworder = new Point();
                                        int layers = 0;

                                        while ((targfound == false) & (layers <= 5))
                                        {
                                            layers++;
                                            for (int nx = 0 - layers; nx <= layers; nx++)
                                            {
                                                if (targfound == false)
                                                {
                                                    for (int ny = 0 - layers; ny <= layers; ny++)
                                                    {
                                                        if (targfound == false)
                                                        {
                                                            if (GetTerrain(orderx + nx, ordery + ny) == TerrainType.Clear)
                                                            {
                                                                targfound = true;
                                                                neworder.X = orderx + nx;
                                                                neworder.Y = ordery + ny;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        if (targfound == true)
                                        {
                                            //found a clearing so move there instead.
                                            orderx = (int)neworder.X;
                                            ordery = (int)neworder.Y;
                                            Move(ship, orderx, ordery);
                                        }
                                    }
                                }
                                PrintToDebug("STT " + ship.Code + " task end", EnD);
                                #endregion
                            }
                            if (ship.ShipType == StarShipType.CloakDetector)
                            {
                                #region CloakDetector Code
                                PrintToDebug("CDD " + ship.Code, EnD);
                                if (ship.CloakArrows.Count > 1)
                                {
                                    ClearOrder(ship);
                                }
                                else
                                {
                                    ad2 = GetStarSystemIndex(mycap.Name);
                                    Melees[ad2] = Melees[ad2] + 1;
                                    ad1 = (Melees[ad2] / 2) + 1;
                                    if (ad1 < 1) ad1 = 1;
                                    Move(ship, mycap.X + Random(0 - ad1, ad1), mycap.Y + Random(0 - ad1, ad1));
                                }
                                #endregion
                            }
                            if (ship.ShipType == StarShipType.RepairShip)
                            {
                                #region RepairShip Code
                                PrintToDebug("RSS " + ship.Code + " repairship processing", EnD);
                                //SendMessage(ChatChannel.All, "DebugRS");
                                shiphealth = 100;
                                tarShip1 = null;
                                tarShip2 = null;
                                intClosest = 32767;
                                intcloseststb = -1;  //used as index
                                floArcdist = 100;  //used as second health
                                for (int d = 0; d < fieldunits; d++)
                                {
                                    intDSDist = DistanceQuick(ship.X, ship.Y, TRepair[d].X, TRepair[d].Y);
                                    if ((TRepair[d].Health < shiphealth) & (intClosest >= intDSDist) & (TRepairLock[d] == 0))
                                    {
                                        shiphealth = TRepair[d].Health;
                                        tarShip1 = TRepair[d];
                                        intcloseststb = d;
                                        intClosest = intDSDist;
                                    }
                                    if ((TRepair[d].Health < floArcdist) & (TRepairLock[d] == 1) & (tarShip1 != null))
                                    {
                                        floArcdist = TRepair[d].Health;
                                        tarShip2 = TRepair[d];
                                    }
                                }
                                if (ship.Health < 100)
                                {
                                    Target(ship, ship);  //order repairship to repair itself.
                                }
                                else if ((shiphealth < 100) & (tarShip1 != null))
                                {
                                    TRepairLock[intcloseststb] = 1;
                                    Target(ship, tarShip1);
                                }
                                else if ((floArcdist < 100) & (tarShip2 != null))
                                {
                                    Target(ship, tarShip2);
                                }
                                else
                                {
                                    if (((ship.X >= mycapx - 4) & (ship.Y >= mycapy - 4) & (ship.X <= mycapx + 4) & (ship.Y <= mycapy + 4)) &
                                       (((ship.X >= mycapx - 1) & (ship.Y >= mycapy - 1) & (ship.X <= mycapx + 1) & (ship.Y <= mycapy + 1)) == false))
                                        ClearOrder(ship);
                                    else
                                        Move(ship, mycapx - 2, mycapy - 2);
                                }
                                //SendMessage(ChatChannel.All, "EDebugRS");
                                PrintToDebug("RSS " + ship.Code + " end repairship processing", EnD);
                                #endregion
                            }
                            if ((ship.ShipType == StarShipType.DoomMissile) | (ship.ShipType == StarShipType.NukeMissile))
                            {
                                #region Doom and Nuke Missile Code
                                PrintToDebug("DOOM " + ship.Code, EnD);
                                if ((SE == true) & (CalAttack == true))
                                    Target(ship, Ecap);
                                #endregion
                            }
                            if (ship.ShipType == StarShipType.BattleStation)
                            {
                                #region BattleStation Code
                                PrintToDebug("BTS " + ship.Code, EnD);
                                if (BattleStationRepairMode == true)
                                {
                                    ClearOrder(ship);
                                }
                                else if (cloaker == false)
                                {
                                    tarStar1 = ClosestStarSystem(ship.X, ship.Y, 32767, FindSystemFlags.Unfriendly);
                                    Target(ship, tarStar1);
                                }
                                else
                                {
                                    Move(ship, mycapx + Random(-20, 20), mycapy + Random(-20, 20));
                                }
                                //assist the startillery building.
                                if (SE == false)
                                {
                                    BuildStarShip(ship, StarShipType.StarTillery, 20, TRange, cloaker);
                                }
                                else
                                {
                                    BuildStarShip(ship, StarShipType.WarShip, wareng3, cavalrywpn + 1, cloaker);
                                }
                                #endregion
                            }
                            if (ship.ShipType == StarShipType.MineSweeper)
                            {
                                #region MineSweeper Code
                                PrintToDebug("MINESW " + ship.Code, EnD);
                                stari = mycap;
                                if ((SE == true) & (CalAttack == true))
                                {
                                    Move(ship, Ecapx, Ecapy);
                                }
                                else
                                {
                                    ad2 = GetStarSystemIndex(stari.Name);
                                    Melees[ad2] = Melees[ad2] + 1;
                                    ad1 = (Melees[ad2] / 2) + 1;
                                    if (ad1 < 1) ad1 = 1;
                                    Move(ship, stari.X + Random(0 - ad1, ad1), stari.Y + Random(0 - ad1, ad1));
                                }
                                #endregion
                            }
                            if (ship.ShipType == StarShipType.GravShip)
                            {
                                //if using SV6.0, uncomment the pulsar tugging code!
                                #region Gravship Code

                                PrintToDebug("GRAVSHIP " + ship.Code, EnD);
                                if (_shipTargetOrder.ContainsKey(ship.Code) == false)
                                    _shipTargetOrder.Add(ship.Code, null);
                                if (ship.Dragging == null)
                                {
                                    tarStar2 = null;
                                    intClosest = 32767;
                                    if (tarStar2 == null)
                                    {
                                        foreach (StarSystemInfo dragsys in StarSystems)
                                        {
                                            intDSDistb = DistanceQuick(dragsys.X, dragsys.Y, mycapx, mycapy);
                                            if ((intDSDistb <= mycap.Scanners + 4) & (_GravShipDragComplete[dragsys.Name] != 2))
                                                _GravShipDragComplete[dragsys.Name] = 2;
                                            else if (intDSDistb > mycap.Scanners + 4)
                                                _GravShipDragComplete[dragsys.Name] = 0;

                                            intDSDist = DistanceQuick(ship.X, ship.Y, dragsys.X, dragsys.Y);
                                            if ((intDSDist <= intClosest) & (_GravShipDragComplete[dragsys.Name] == 0))
                                            {
                                                tarStar2 = dragsys;
                                                intClosest = intDSDist;
                                            }
                                        }
                                    }
                                    if (tarStar2 != null)
                                    {
                                        Target(ship, tarStar2);
                                        _GravShipDragComplete[tarStar2.Name] = 1;
                                        _shipTargetOrder[ship.Code] = tarStar2;
                                    }
                                }
                                else
                                {
                                    if (_shipTargetOrder[ship.Code] == null)
                                    {
                                        tarStar1 = ClosestStarSystem(ship.X, ship.Y, 3, FindSystemFlags.All);
                                        if (tarStar1 != null)
                                            if (_GravShipDragComplete[tarStar1.Name] == 0)
                                                tarStar2 = tarStar1;

                                        _GravShipDragComplete[tarStar2.Name] = 1;
                                        _shipTargetOrder[ship.Code] = tarStar2;

                                    }
                                    else
                                    {
                                        tarStar2 = _shipTargetOrder[ship.Code];
                                    }
                                    _GravShipDragComplete[tarStar2.Name] = 1;
                                    Move(ship, mycapx, mycapy);
                                    if ((Distance(ship.X, ship.Y, mycapx, mycapy) <= mycap.Scanners) & (Random(1, 10) >= 9))
                                    {
                                        ClearOrder(ship);
                                        Release(ship);
                                        _GravShipDragComplete[tarStar2.Name] = 2;
                                        _shipTargetOrder[ship.Code] = null;
                                    }
                                }
                                #endregion
                            }
                            if (ship.ShipType == StarShipType.JumpGateShip)
                            {
                                #region JumpGateShip Code
                                PrintToDebug("JumpGate " + ship.Code, EnD);
                                stari = mycap;
                                if ((SE == true) & (CalAttack == true))
                                {
                                    Move(ship, Ecapx, Ecapy);
                                    destx = Math.Abs(ship.X - Ecapx);
                                    desty = Math.Abs(ship.Y - Ecapy);
                                    if (destx < desty) intDSDist = desty;
                                    else intDSDist = destx;
                                    if (intDSDist < 12)
                                        CreateJumpGate(ship);
                                }
                                else
                                {
                                    ad2 = GetStarSystemIndex(stari.Name);
                                    Melees[ad2] = Melees[ad2] + 1;
                                    ad1 = (Melees[ad2] / 2) + 1;
                                    if (ad1 < 1) ad1 = 1;
                                    Move(ship, stari.X + Random(0 - ad1, ad1), stari.Y + Random(0 - ad1, ad1));
                                }
                                #endregion
                            }
                            if (ship.ShipType == StarShipType.Tug)
                            {
                                #region Tug Code
                                PrintToDebug("TUG " + ship.Code, EnD);
                                tarShip1 = ClosestStarShip(ship.X, ship.Y, 32767, FindShipFlags.Enemy, ShipKnownFlags.Either);
                                if (ship.Tugging == null)
                                {
                                    if (tarShip1 != null)
                                    {
                                        Target(ship, tarShip1);
                                    }
                                    else
                                    {
                                        ad2 = GetStarSystemIndex(mycap.Name);
                                        Melees[ad2] = Melees[ad2] + 1;
                                        ad1 = (Melees[ad2] / 2) + 1;
                                        if (ad1 < 1) ad1 = 1;
                                        Move(ship, mycapx + Random(0 - ad1, ad1), mycapy + Random(0 - ad1, ad1));
                                    }
                                }
                                else
                                {
                                    destx = Math.Abs(ship.X - mycapx);
                                    desty = Math.Abs(ship.Y - mycapy);
                                    if (destx < desty) intDSDist = desty;
                                    else intDSDist = destx;
                                    if (intDSDist < 12)
                                        ClearOrder(ship);
                                    else
                                        Move(ship, mycapx, mycapy);
                                }
                                #endregion
                            }
                            if (ship.ShipType == StarShipType.ShieldGenerator)
                            {
                                #region ShieldGenerator Code
                                PrintToDebug("SG " + ship.Code, EnD);
                                if (_shipTargetOrder.ContainsKey(ship.Code) == false)
                                    _shipTargetOrder.Add(ship.Code, null);

                                if (_shipTargetOrder[ship.Code] == null)
                                {
                                    tarStar1 = null;
                                    for (int d = 0; d < mystars; d++)
                                        if (mystar[d].Value >= 12)
                                        {
                                            ad1 = GetStarSystemIndex(mystar[d].Name);
                                            if (SG[ad1] == 0)
                                                tarStar1 = mystar[d];
                                        }
                                    if (tarStar1 != null)
                                    {
                                        ad1 = GetStarSystemIndex(tarStar1.Name);
                                        SG[ad1] = 1;
                                        Target(ship, tarStar1);
                                        _shipTargetOrder[ship.Code] = tarStar1;
                                    }
                                    else
                                    {
                                        tarStar1 = ClosestStarSystem(ship.X, ship.Y, 32767, FindSystemFlags.Friendly);
                                        ad1 = GetStarSystemIndex(tarStar1.Name);
                                        SG[ad1] = 1;
                                        Target(ship, tarStar1);
                                        _shipTargetOrder[ship.Code] = tarStar1;
                                    }
                                }
                                else
                                {
                                    tarStar1 = _shipTargetOrder[ship.Code];
                                    ad1 = GetStarSystemIndex(tarStar1.Name);
                                    SG[ad1] = 1;
                                    if (tarStar1.OwnedByMe == false)
                                    {
                                        tarStar1 = ClosestStarSystem(ship.X, ship.Y, 32767, FindSystemFlags.Friendly);
                                        ad1 = GetStarSystemIndex(tarStar1.Name);
                                        SG[ad1] = 1;
                                        Target(ship, tarStar1);
                                        _shipTargetOrder[ship.Code] = tarStar1;
                                    }
                                }
                                #endregion
                            }
                            if (ship.ShipType == StarShipType.MadBomb)
                            {
                                #region MadBomb Code
                                PrintToDebug("MDB " + ship.Code, EnD);
                                stari = mycap;
                                if ((SE == true) & (CalAttack == true))
                                {
                                    Move(ship, Ecapx, Ecapy);
                                    destx = Math.Abs(ship.X - Ecapx);
                                    desty = Math.Abs(ship.Y - Ecapy);
                                    if (destx < desty) intDSDist = desty;
                                    else intDSDist = destx;
                                    if (intDSDist < (ship.Engines / 2) + 2)
                                        DetonateMadBomb(ship);
                                }
                                else
                                {
                                    ad2 = GetStarSystemIndex(stari.Name);
                                    Melees[ad2] = Melees[ad2] + 1;
                                    ad1 = (Melees[ad2] / 2) + 1;
                                    if (ad1 < 1) ad1 = 1;
                                    Move(ship, stari.X + Random(0 - ad1, ad1), stari.Y + Random(0 - ad1, ad1));
                                }
                                #endregion
                            }
                            //place additoinal starships here
                        }
                        s = s + 1;
                    }
                    //END OF STANDARD MODE
                    for (int d = 0; d < 12; d++)
                    {
                        laststarsowned[d] = starsowned[d];
                    }
                    #endregion

                }
                else
                {
                    #region Extreme Duel Code
                    //Reserve a spot to place ED Code
                    //SendMessage(ChatChannel.All, "THIS IS ED!");
                    int fortifycount = 0;
                    //int stage = 0;
                    StarSystemInfo mycap = null;
                    StarSystemInfo ecap = null;
                    bool topleft = true;
                    foreach (StarSystemInfo sys in StarSystems)
                    {
                        if (sys.OwnedByMe == true)
                        {
                            mycap = sys;
                            if (sys.Shields < sys.Value / 9)
                                BuildShields(sys, (sys.Value / 9) - sys.Shields);
                        }
                        else
                        {
                            ecap = sys;
                        }
                    }
                    int mycapx = 0;
                    int mycapy = 0;
                    int ecapx = 0;
                    int ecapy = 0;
                    if (mycap != null)
                    {
                        mycapx = mycap.X;
                        mycapy = mycap.Y;
                        if (ecap != null)
                        {
                            ecapx = ecap.X;
                            ecapy = ecap.Y;
                            if ((ecapx < mycapx) | (ecapy < mycapy))
                                topleft = false;
                        }
                    }

                    int WSs = 0;
                    int STs = 0;
                    int CDs = 0;
                    int TSs = 0;
                    int HJs = 0;
                    int Others = 0;
                    bool BlockAlert = false;
                    bool Attack = false;
                    bool EnemyBlocked = false;
                    int myblockcount = 0;
                    int hisblockcount = 0;
                    int Threat = 0;
                    int Power = 0;
                    StarShipInfo[] CloakD = new StarShipInfo[100];
                    foreach (StarShipInfo ship in StarShips)
                    {
                        if (ship.OwnedByMe == true)
                        {
                            if (ecap != null)
                            {
                                if (DistanceQuick(ship.X, ship.Y, ecapx, ecapy) <= 50)
                                    fortifycount++;
                                if ((ship.X >= ecapx - 1) & (ship.Y >= ecapy - 1) & (ship.X <= ecapx + 1) & (ship.Y <= ecapy + 1))
                                    hisblockcount++;
                            }
                            if (ship.ShipType == StarShipType.WarShip)
                            {
                                WSs++;
                                if (ecap != null)
                                {
                                    if ((ship.X >= ecapx - 10) & (ship.Y >= ecapy - 10) & (ship.X <= ecapx + 10) & (ship.Y <= ecapy + 10))
                                    {
                                        Power = Power + ship.Value;
                                        if (Power > Math.Round(ecap.Shields * 1.1))
                                            Attack = true;
                                    }
                                }
                            }
                            else if (ship.ShipType == StarShipType.StarTillery)
                            {
                                STs++;
                            }
                            else if (ship.ShipType == StarShipType.TechShip)
                            {
                                TSs++;
                            }
                            else if (ship.ShipType == StarShipType.CloakDetector)
                            {
                                CDs++;
                                if (ship.CloakArrows.Count > 0)
                                    if (Threat <= 1)
                                        Threat = 2;
                                CloakD[CDs - 1] = ship;
                            }
                            else if (ship.ShipType == StarShipType.HijackShip)
                            {
                                HJs++;
                                Others++;
                            }
                            else
                            {
                                Others++;
                            }
                        }
                        else
                        {
                            if (ship.Cloaked == true)
                                if (DistanceQuick(ship.X, ship.Y, mycapx, mycapy) <= 30)
                                    Threat = 1;
                            if ((ship.X >= mycapx - 1) & (ship.Y >= mycapy - 1) & (ship.X <= mycapx + 1) & (ship.Y <= mycapy + 1))
                                myblockcount++;
                        }
                    }

                    if (Countdown == -1)
                        Countdown = 13;

                    int ThresholdH = 120;
                    int ThresholdM = 50;
                    if ((fortifycount >= ThresholdH) | (STs + (Others * 2) >= ThresholdH * 3) | (hisblockcount > 0))
                        ExecuteBlock = true;
                    else if ((fortifycount < ThresholdM) & (hisblockcount == 0))
                    {
                        if (ExecuteBlock == true) Countdown = Countdown - 1;
                        ExecuteBlock = false;
                    }

                    if (myblockcount > 0)
                    {
                        if (myblockcount >= 8) BlockAlert = true;
                        if (Threat <= 2) Threat = 3;
                    }
                    if ((hisblockcount >= 8) | (Attack == true))
                        EnemyBlocked = true;

                    if (mycap != null)
                    {
                        int Res = mycap.Resources;
                        int Val = mycap.Value;
                        if (TSs < 20)
                        {
                            if (topleft == false)
                            {
                                if (EnemyBlocked == true)
                                    for (int d = 0; d < 3; d++)
                                        BuildStarShip(mycap, StarShipType.TechShip, 3, 0, true);

                                for (int d = 0; d < 2; d++)
                                    BuildStarShip(mycap, StarShipType.TechShip, 3, 0, true);
                            }
                            if (Res >= 3000)
                                BuildStarShip(mycap, StarShipType.StarTillery, 20, 25, true);
                            else if (ecap != null)
                                BuildStarShip(mycap, StarShipType.InkSpot, 20, 0, (Random(0, 100) < 95));
                            if (EnemyBlocked == false)
                                for (int d = 0; d < 5; d++)
                                    BuildStarShip(mycap, StarShipType.HijackShip, 20, 0, true);
                            if (topleft == true)
                            {
                                if (EnemyBlocked == true)
                                    for (int d = 0; d < 3; d++)
                                        BuildStarShip(mycap, StarShipType.TechShip, 3, 0, true);

                                for (int d = 0; d < 2; d++)
                                    BuildStarShip(mycap, StarShipType.TechShip, 3, 0, true);
                            }
                        }
                        else if (Threat >= 1)
                        {
                            BuildStarShip(mycap, StarShipType.InkSpot, 20, 0, (Random(0, 100) < 95));
                            for (int d = 0; d < 7; d++)
                                BuildStarShip(mycap, StarShipType.HijackShip, 20, 0, true);
                        }
                        else if (Res >= 40000)
                        {
                            for (int d = 0; d < 4; d++)
                            {
                                BuildStarShip(mycap, StarShipType.StarTillery, 20, 45, true);
                                BuildStarShip(mycap, StarShipType.WarShip, 20, 100, true);
                            }
                        }
                        else if (Res >= 20000)
                        {
                            if (STs < ThresholdH)
                            {
                                for (int d = 0; d < 8; d++)
                                    BuildStarShip(mycap, StarShipType.StarTillery, 20, 25, true);
                            }
                            else
                            {
                                for (int d = 0; d < 8; d++)
                                    BuildStarShip(mycap, StarShipType.HijackShip, 20, 0, true);
                            }
                        }
                        else if (CDs < 2)
                        {
                            for (int d = 0; d < 2; d++)
                                BuildStarShip(mycap, StarShipType.CloakDetector, 20, 20, true);
                        }
                        else if (STs <= (fortifycount / 4) - 1)
                        {
                            for (int d = 0; d < 8; d++)
                                BuildStarShip(mycap, StarShipType.StarTillery, 20, 25, true);
                        }
                        else if (EnemyBlocked == true)
                        {
                            for (int d = 0; d < 8; d++)
                                BuildStarShip(mycap, StarShipType.WarShip, 20, Random(21, 26), true);
                        }
                        else if (fortifycount <= ThresholdM)
                        {
                            if (HJs < 45)
                            {
                                for (int d = 0; d < 4; d++)
                                {
                                    BuildStarShip(mycap, StarShipType.InkSpot, 20, 0, (Random(0, 100) < 95));
                                    BuildStarShip(mycap, StarShipType.HijackShip, 20, 0, true);
                                }
                            }
                            else
                            {
                                for (int d = 0; d < 8; d++)
                                    BuildStarShip(mycap, StarShipType.InkSpot, 20, 0, (Random(0, 100) < 95));
                            }
                        }
                        else
                        {
                            for (int d = 0; d < 8; d++)
                            {
                                BuildStarShip(mycap, StarShipType.InkSpot, 20, 0, (Random(0, 100) < 95));
                                BuildStarShip(mycap, StarShipType.HijackShip, 20, 0, true);
                            }
                        }
                    }


                    int CC = 0;
                    int BDrones = 0;
                    int BInkspots = 0;
                    int BStartilleries = 0;
                    int BHijacks = 0;
                    int intclosestdist = 0;
                    int intDSDist = 0;
                    int mx = 0;
                    int my = 0;
                    int irange = 0;
                    double floArcDist = 0;
                    int Attacks = 0;
                    int orderx = 0;
                    int ordery = 0;
                    bool detectedcloaked = false;
                    StarShipInfo idefend = null;
                    StarShipInfo tempi = null;
                    foreach (StarShipInfo ship in MyStarShips)
                    {
                        if (ship.ShipType == StarShipType.WarShip)
                        {
                            if (Attack == true)
                            {
                                Target(ship, ecap);
                            }
                            else if (EnemyBlocked == true)
                            {
                                if (topleft == true) Move(ship, ecapx - 4, ecapy - 4);
                                else Move(ship, ecapx + 4, ecapy + 4);
                            }
                            else if ((ecap != null) & (ship.Value >= 13))
                            {
                                if (topleft == false) Move(ship, mycapx - 12, mycapy - 12);
                                else Move(ship, mycapx + 12, mycapy + 12);
                            }
                        }
                        else if (ship.ShipType == StarShipType.CloakDetector)
                        {
                            CC++;
                            if (CC == 1)
                            {
                                if (topleft == false) Move(ship, mycapx - 11, mycapy - 20);
                                else Move(ship, mycapx + 11, mycapy + 20);
                            }
                            else if (CC == 2)
                            {
                                if (topleft == false) Move(ship, mycapx - 20, mycapy - 11);
                                else Move(ship, mycapx + 20, mycapy + 11);
                            }
                            else
                            {
                                if (topleft == false) Move(ship, mycapx - 20, mycapy - 20);
                                else Move(ship, mycapx + 20, mycapy + 20);
                            }
                        }
                        else if (ship.ShipType == StarShipType.TechShip)
                        {
                            if ((ship.X >= ecapx - 1) & (ship.Y >= ecapy - 1) & (ship.X <= ecapx + 1) & (ship.Y <= ecapy + 1) & (Attack == false))
                            {
                                ClearOrder(ship);
                            }
                            else
                            {
                                if (topleft == false) Move(ship, mycapx - 12, mycapy - 12);
                                else Move(ship, mycapx + 12, mycapy + 12);
                            }
                        }
                        else if (ship.ShipType == StarShipType.Drone)
                        {
                            BDrones++;
                            AttackAdjacent(ship, true);
                            if ((BDrones < 40) & (ExecuteBlock == false))
                            {
                                //shield the capital
                                if (topleft == false) Move(ship, ecapx + (Countdown + 5), ecapy - (Countdown + 5));
                                else Move(ship, ecapx - (Countdown + 5), ecapy - (Countdown + 5));
                            }
                            else
                            {
                                //Build the fort
                                if ((fortifycount < ThresholdH) & (ExecuteBlock == false))
                                {
                                    if (topleft == true)
                                    {
                                        if (Random(0, 100) > 50) Move(ship, ecapx - 25, ecapy - 15);
                                        else Move(ship, ecapx - 15, ecapy - 25);
                                    }
                                    else
                                    {
                                        if (Random(0, 100) > 50) Move(ship, ecapx + 25, ecapy + 15);
                                        else Move(ship, ecapx + 15, ecapy + 25);
                                    }
                                }
                                else
                                {
                                    if (EnemyBlocked == true)
                                    {
                                        if ((ship.X >= ecapx - 1) & (ship.Y >= ecapy - 1) & (ship.X <= ecapx + 1) & (ship.Y <= ecapy + 1) & (Attack == false))
                                        {
                                            ClearOrder(ship);
                                        }
                                        else
                                        {
                                            if (topleft == false) Move(ship, Random(ecapx, mycapx + 1), Random(ecapy, mycapy + 1));
                                            else Move(ship, Random(mycapx, ecapx + 1), Random(mycapy, ecapy + 1));
                                        }
                                    }
                                    else
                                    {
                                        Move(ship, ecapx, ecapy);
                                    }
                                }
                            }
                        }
                        else if (ship.ShipType == StarShipType.InkSpot)
                        {
                            //Order gaurd Cloak Detectors
                            if (BlockAlert == false)
                            {
                                BInkspots++;
                                if (BInkspots < 8)
                                {
                                    idefend = null;
                                    intclosestdist = 9999;
                                    for (int a = 0; a < CDs; a++)
                                    {
                                        tempi = CloakD[a];
                                        intDSDist = DistanceQuick(ship.X, ship.Y, tempi.X, tempi.Y);
                                        if (intDSDist < intclosestdist)
                                        {
                                            idefend = tempi;
                                            intclosestdist = intDSDist;
                                        }
                                    }
                                    if (idefend != null)
                                    {
                                        detectedcloaked = false;
                                        if (idefend.CloakArrows.Count > 0) detectedcloaked = true;
                                        if (detectedcloaked == true)
                                        {
                                            if (topleft == true)
                                            {
                                                if (Distance(ship.X, ship.Y, mycapx + 15, mycapy) < Distance(ship.X, ship.Y, mycapx, mycapy + 15))
                                                    Move(ship, mycapx + 15, mycapy);
                                                else
                                                    Move(ship, mycapx, mycapy + 15);
                                            }
                                            else
                                            {
                                                if (Distance(ship.X, ship.Y, mycapx - 15, mycapy) < Distance(ship.X, ship.Y, mycapx, mycapy - 15))
                                                    Move(ship, mycapx - 15, mycapy);
                                                else
                                                    Move(ship, mycapx, mycapy - 15);
                                            }
                                        }
                                        else
                                        {
                                            Move(ship, idefend.X + Random(-12, 12), idefend.Y + Random(-12, 12));
                                        }
                                    }
                                    else
                                    {
                                        if (topleft == false) Move(ship, Random(ecapx, mycapx + 1), Random(ecapy, mycapy + 1));
                                        else Move(ship, Random(mycapx, ecapx + 1), Random(mycapy, ecapy + 1));
                                    }
                                }
                                else
                                {
                                    if ((fortifycount < ThresholdH) & (ExecuteBlock == false))
                                    {
                                        Move(ship, ecapx, ecapy);
                                    }
                                    else
                                    {
                                        if (EnemyBlocked == true)
                                        {
                                            if ((ship.X >= ecapx - 1) & (ship.Y >= ecapy - 1) & (ship.X <= ecapx + 1) & (ship.Y <= ecapy + 1) & (Attack == false))
                                            {
                                                ClearOrder(ship);
                                            }
                                            else
                                            {
                                                if (topleft == false) Move(ship, Random(ecapx, mycapx + 1), Random(ecapy, mycapy + 1));
                                                else Move(ship, Random(mycapx, ecapx + 1), Random(mycapy, ecapy + 1));
                                            }
                                        }
                                        else
                                        {
                                            Move(ship, ecapx, ecapy);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (topleft == true) Move(ship, mycapx + 10, mycapy + 10);
                                else Move(ship, mycapx - 10, mycapy - 10);
                            }
                        }
                        else if (ship.ShipType == StarShipType.StarTillery)
                        {
                            BStartilleries++;
                            if (_shipStarted.ContainsKey(ship.Code) == false)
                                _shipStarted.Add(ship.Code, -1);

                            if ((ExecuteBlock == false) | (BStartilleries < 25))
                            {
                                tempi = ClosestStarShip(ship.X, ship.Y, 32767, FindShipFlags.Enemy, ShipKnownFlags.Either);
                                if ((Threat <= 1) & (BlockAlert == false) & (_shipStarted[ship.Code] == 2))
                                {
                                    mx = Math.Abs(ship.X - ecapx);
                                    my = Math.Abs(ship.Y - ecapy);
                                    orderx = ecapx;
                                    ordery = ecapy;
                                }
                                else
                                {
                                    if (_shipStarted[ship.Code] < 2)
                                        _shipStarted[ship.Code]++;
                                    mx = Math.Abs(ship.X - mycapx);
                                    my = Math.Abs(ship.Y - mycapy);
                                    orderx = mycapx;
                                    ordery = mycapy;
                                }
                                if ((tempi != null) & (_shipStarted[ship.Code] == 2))
                                {
                                    mx = Math.Abs(ship.X - tempi.X);
                                    my = Math.Abs(ship.Y - tempi.Y);
                                    orderx = tempi.X;
                                    ordery = tempi.Y;
                                }
                                mx = mx * mx;
                                my = my * my;
                                floArcDist = Math.Sqrt(mx + my);
                                irange = ship.Value - 2;
                                if (irange < 5) irange = 5;
                                orderx = orderx + Convert.ToInt32((ship.X - orderx) / (floArcDist / irange));
                                ordery = ordery + Convert.ToInt32((ship.Y - ordery) / (floArcDist / irange));
                                Move(ship, orderx, ordery);
                            }
                            else
                            {
                                if (EnemyBlocked == true)
                                {
                                    if ((ship.X >= ecapx - 1) & (ship.Y >= ecapy - 1) & (ship.X <= ecapx + 1) & (ship.Y <= ecapy + 1) & (Attack == false))
                                    {
                                        ClearOrder(ship);
                                    }
                                    else
                                    {
                                        if (topleft == false) Move(ship, Random(ecapx, mycapx + 1), Random(ecapy, mycapy + 1));
                                        else Move(ship, Random(mycapx, ecapx + 1), Random(mycapy, ecapy + 1));
                                    }
                                }
                                else
                                {
                                    Move(ship, ecapx, ecapy);
                                }
                            }
                        }
                        else if (ship.ShipType == StarShipType.HijackShip)
                        {
                            AttackAdjacent(ship, true);
                            BHijacks++;
                            Attacks = 8;
                            if (((BHijacks < 70) & (BlockAlert == false)) | ((Threat <= 1) & (BHijacks >= 80)))
                            {
                                if ((BHijacks < 50) & ((BHijacks > 40 - Attacks) | (BHijacks <= Attacks)) & (ExecuteBlock == false))
                                {
                                    if (topleft == true) Move(ship, ecapx - ((Countdown * 2) - 13), ecapy - ((Countdown * 2) - 13));
                                    else Move(ship, ecapx + ((Countdown * 2) - 13), ecapy + ((Countdown * 2) - 13));
                                }
                                else if ((BHijacks < 60) & (ExecuteBlock == false))
                                {
                                    if (topleft == true)
                                    {
                                        if (Random(0, 100) > 50) Move(ship, mycapx + 9, mycapy);
                                        else Move(ship, mycapx, mycapy + 9);
                                    }
                                    else
                                    {
                                        if (Random(0, 100) > 50) Move(ship, mycapx - 9, mycapy);
                                        else Move(ship, mycapx, mycapy - 9);
                                    }
                                }
                                else
                                {
                                    if (EnemyBlocked == true)
                                    {
                                        if ((ship.X >= ecapx - 1) & (ship.Y >= ecapy - 1) & (ship.X <= ecapx + 1) & (ship.Y <= ecapy + 1) & (Attack == false))
                                        {
                                            ClearOrder(ship);
                                        }
                                        else
                                        {
                                            if (topleft == false) Move(ship, Random(ecapx, mycapx), Random(ecapy, mycapy));
                                            else Move(ship, Random(mycapx, ecapx), Random(mycapy, ecapy));
                                        }
                                    }
                                    else
                                    {
                                        Move(ship, ecapx, ecapy);
                                    }
                                }
                            }
                            else
                            {
                                tempi = ClosestStarShip(ship.X, ship.Y, 20, FindShipFlags.Enemy, ShipKnownFlags.Either);
                                if (tempi != null)
                                {
                                    Move(ship, tempi.X, tempi.Y);
                                }
                                else
                                {
                                    if (topleft == true) Move(ship, mycapx + 5, mycapy + 5);
                                    else Move(ship, mycapx - 5, mycapy - 5);
                                }
                            }
                        }
                        else
                        {
                            if (ExecuteBlock == false)
                            {
                                Move(ship, ecapx, ecapy);
                            }
                            else
                            {
                                if (EnemyBlocked == true)
                                {
                                    if ((ship.X >= ecapx - 1) & (ship.Y >= ecapy - 1) & (ship.X <= ecapx + 1) & (ship.Y <= ecapy + 1) & (Attack == false))
                                    {
                                        ClearOrder(ship);
                                    }
                                    else
                                    {
                                        if (topleft == false) Move(ship, Random(ecapx, mycapx), Random(ecapy, mycapy));
                                        else Move(ship, Random(mycapx, ecapx), Random(mycapy, ecapy));
                                    }
                                }
                                else
                                {
                                    Move(ship, ecapx, ecapy);
                                }
                            }
                        }
                    }
                    #endregion
                }

                PrintToDebug("End of " + Name + " debug session. Press a key to continue with gameplay.", EnD);

                if (debuggerenabled == true)
                {
                    ShowDebugScreen();
                    SendMessage(ChatChannel.All, "Attention, " + Name + " is experiencing technicial diffuculties and must be debugged.");
                }

                if (_ReadMessage.Count > 0)
                {
                    _ReadMessage.Clear();
                    _SentByPlayer.Clear();
                }
                totalmessagesreceived = 0;
            }
            catch (Exception ex)
            {
                //ERROR CATCHER!!
                //MessageBox.Show("An Error with Stratego 4 has occurred. Launching Debug applet.");

                PrintToDebug("================================================================", EnD);
                PrintToDebug("An error has occurred with " + Name + ". Please send this debug script to author's E-Mail.", EnD);
                PrintToDebug("================================================================", EnD);

                PrintToDebug(ex.ToString(), EnD);

                PrintToDebug("End of " + Name + " debug session.. Press a key to continue with gameplay..", EnD);

                ShowDebugScreen();
                SendMessage(ChatChannel.All, "Attention, " + Name + " is experiencing technicial diffuculties and must be debugged.");
            }
        }

        #region Player Communications Class
        public void ConvertStarShipList(string StarShipList, List<string> output)
        {
            string[] tmpstr;
            string[] sepr = new string[1];
            sepr[0] = ",";

            tmpstr = StarShipList.Split(sepr, StringSplitOptions.RemoveEmptyEntries);

            for (int ad = 0; ad < tmpstr.Length; ad++)
            {
                output.Insert(ad, tmpstr[ad]);
            }
        }

        //Player Communications Module. Allows brains to chat with Human Players. 
        //Can even interpret txt message language. Created by Beat2k.
        internal class PlayerCommunications
        {
            public bool IsPositive(string message)
            {
                message = message.ToLower();
                if ((message == "yep") | (message == "yes") | (message == "ok") |
                    (message == "k") | (message == "yeppers") | (message == "sure") |
                    (message == "yeah") | (message == "go") | (message == "accepted") |
                    (message == "good") | (message == "accept") | (message == "si") |
                    (message == "always") | (message == "we") | (message == "yea") |
                    (message == "do") | (message == "fine") | (message == "10-4") |
                    (message == "yes,"))
                    return true;
                else
                    return false;
            }

            public bool IsNegative(string message)
            {
                message = message.ToLower();
                if ((message == "nope") | (message == "no") | (message == "never") |
                    (message == "nok") | (message == "not") | (message == "naw") |
                    (message == "nay") | (message == "stop") | (message == "unaccepted") |
                    (message == "bad") | (message == "declined") | (message == "don't") |
                    (message == "no,"))
                    return true;
                else
                    return false;
            }

            public void BreakDownMessageIntoWords(string message, List<string> output)
            {
                string[] tmpstr;
                string[] sepr = new string[1];

                sepr[0] = " ";

                tmpstr = message.Split(sepr, StringSplitOptions.RemoveEmptyEntries);

                for (int ad = 0; ad < tmpstr.Length; ad++)
                    output.Insert(ad, tmpstr[ad]);
            }

            //Used for processing starship orders
            public int OneWordResponse(string message)
            {
                if (IsNegative(message) == true)
                    return 1;
                else if (IsPositive(message) == true)
                    return 2;
                else
                    return 0;
            }

            public bool IsMessageAdressedToMe(string myname, string message)
            {
                int lengthofmyname = 0;
                int lengthofmessage = 0;
                message = message.ToLower();
                myname = myname.ToLower();
                lengthofmyname = myname.Length;
                lengthofmessage = message.Length;
                if (lengthofmyname < lengthofmessage)
                {
                    if (message.Substring(lengthofmyname, 1) == ",")
                    {
                        if (message.Substring(0, lengthofmyname) == myname)
                            return true;
                        else
                            return false;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }

        }
        #endregion

    }

}
